【问题标题】:Problem with async/await and http client requestsasync/await 和 http 客户端请求的问题
【发布时间】:2018-10-23 14:53:59
【问题描述】:
不确定我在这里遗漏了什么,但 console.log() 行打印“Promise { }”而不是响应中的 JSON 正文。
我相信我在使用 async/await 时做错了。
我的代码(快递):
async function axiosPost(url, payload) {
try {
const res = await axios.post(url, payload);
const data = await res.data;
return data;
} catch (error) {
console.error(error);
}
}
app.get('/data', (req, res) => {
data = axiosPost('http://localhost:8080', {
userpass: 'XXX',
method: 'getdata'
});
console.log(data)
res.status(200).send({
message: data
})
});
感谢任何帮助。
【问题讨论】:
标签:
node.js
express
async-await
axios
【解决方案1】:
用这个替换你的路由器。您在进行 API 调用时没有使用 await。希望对您有所帮助。
app.get('/data', async (req, res) => {
let data = await axiosPost('http://localhost:8080', {
userpass: 'XXX',
method: 'getdata'
});
console.log(data)
res.status(200).send({
message: data
})
});
【解决方案2】:
你得到这个结果是因为你没有解决对axiosPost() 的异步调用。这可以通过两种方式解决,一种是将.then() 附加到axiosPost() 调用,或者只是使用await 关键字等待它。见下文:
async function axiosPost(url, payload) {
try {
const res = await axios.post(url, payload);
const data = await res.data; // this is not required but you can leave as is
return data;
} catch (error) {
console.error(error);
}
}
// I converted the callback to an async function and
// also awaited the result from the call to axiosPost(),
// since that is an async function
app.get('/data', async (req, res) => {
data = await axiosPost('http://localhost:8080', {
userpass: 'XXX',
method: 'getdata'
});
console.log(data)
res.status(200).send({
message: data
})
});
// OR using `then()`
app.get('/data', (req, res) => {
axiosPost('http://localhost:8080', {
userpass: 'XXX',
method: 'getdata'
}).then((data) => {
console.log(data);
res.status(200).send({
message: data
});
});
})