异步/等待和HTTP客户端请求出现问题

时间:2018-10-23 04:53:35

标签: node.js express async-await axios

不确定我在这里缺少什么,但是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 个答案:

答案 0 :(得分: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
    })
});

答案 1 :(得分:0)

之所以得到该结果,是因为您没有解决对异步的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
      });
    });
})

相关问题