提问者:小点点

Async/Await和http客户端请求出现问题


不确定这里遗漏了什么,但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
    })
});

感谢任何帮助。


共2个答案

匿名用户

用这个替换路由器。在进行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
    })
});

匿名用户

得到这个结果是因为您没有解析对axiospost()的调用,它是异步的。这可以通过两种方法来解决,一种是将.then()附加到AxiosPost()调用,或者使用Await关键字等待它。见下文:

null

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
      });
    });
})