当我向Postman请求时,我的API返回了正确的数据。即使从React中调用API也是正确的,我在控制器中使用console.log进行了检查,但我总是得到undefined响应。我不确定错误是什么。
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
});
};你能在同样的问题上帮我一下吗?
发布于 2021-11-18 08:34:59
需要在then中返回res才能访问响应:
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
// response is not defined here!
return res;
});
console.log(response);更短的方式:
const response = await axios
.get('certificates', {
params: { sponser }
});
console.log(response);看起来OP对于js来说是相对较新的--我可以推荐这篇介绍给async js:https://javascript.info/async-await的文章。
https://stackoverflow.com/questions/70016641
复制相似问题