我有以下代码:
getData = async function (afgJSON) {
console.log("step 2")
await axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
.then((response) => {
console.log("step 3")
return response.data
})
.catch((e) => {
console.log("step 3")
return e.response.data
})
}
我称之为:
console.log("step 1")
let afgResponse = await common.getData(afgJSON);
console.log("step 4")
console.log(afgResponse)
afgResponse总是未定义的,console.log显示正确的顺序:
步骤1
步骤2
步骤3
步骤4
未定义
但是如果我console.log response.data(.then(,那么响应是好的。
我在stackoverflow上读到了其他关于的帖子。然后=>使用Axios,但我仍然无法理解。
谢谢。
您错过了从函数"返回axios调用的结果;getData";
getData = async function (afgJSON) {
try {
const { data } = await axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
return data
} catch (err) {
return err // return the data you want
}
}
您也可以直接返回axios.post并检查
getData = async function (afgJSON) {
return axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
}
并且在您的另一个文件中=>
const { data: afgResponse } = await common.getData(afgJSON);
但是你必须处理另一个文件中的错误