Node.js 如何使http请求返回它';在路线内的反应
我有一个路由,我希望获取提供给它的数据,并在http请求中发送它,然后在我的路由中返回响应。我所做的是使用这个调用函数发送http请求并返回响应Node.js 如何使http请求返回它';在路线内的反应,node.js,express,http,Node.js,Express,Http,我有一个路由,我希望获取提供给它的数据,并在http请求中发送它,然后在我的路由中返回响应。我所做的是使用这个调用函数发送http请求并返回响应 async function call() { axios .post("https://jsonplaceholder.typicode.com/posts", { title: "foo", body: "bar", userId: 1, }) .then((res) =>
async function call() {
axios
.post("https://jsonplaceholder.typicode.com/posts", {
title: "foo",
body: "bar",
userId: 1,
})
.then((res) => {
return { answer: 30 };
})
.catch((error) => {
console.error(error);
});
}
我试图在路由中调用它,但它不会等待http请求完成。如果您试图让调用
call()
的调用方能够等待axios结果,那么您需要做两件事:
axios.post()
.then()
或等待
.catch()
中的错误。如果您.catch()
只是为了登录而仍然希望将拒绝返回给调用方,则必须重新显示错误。在这种情况下,调用方似乎应该捕获并记录错误function call() {
return axios.post("https://jsonplaceholder.typicode.com/posts", {
title: "foo",
body: "bar",
userId: 1,
}).then((res) => {
return { answer: 30 };
});
}
call().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
此外,这里没有理由使用
async
async
没有神奇的能力知道函数中的异步操作何时完成。您仍然必须返回承诺,或在每个承诺上使用wait
。在这种情况下,由于您没有使用await
,因此没有理由使用async
,因此我删除了它,因为您可以只返回您的一个承诺。我更喜欢@jfriend00的答案,但这里有一个使用async/await的答案
async function over() {
async function call() {
return await axios
.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
})
.then((res) => {
return { answer: 30 };
})
.catch((error) => {
console.error(error);
});
}
let result = await call();
console.log(result);
}
over();
return await axios.post()
中的await
没有意义。这只是额外的开销。