Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使http请求返回它';在路线内的反应_Node.js_Express_Http - Fatal编程技术网

Node.js 如何使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) =>

我有一个路由,我希望获取提供给它的数据,并在http请求中发送它,然后在我的路由中返回响应。我所做的是使用这个调用函数发送http请求并返回响应

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
    没有意义。这只是额外的开销。