繁体   English   中英

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

[英]Problem with async/await and http client requests

不确定我在这里缺少什么,但是console.log()行显示的是“ Promise {}”,而不是响应中的JSON正文。
我相信我在异步/等待时做错了什么。

我的代码(快递):

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

任何帮助表示赞赏。

更换路由器。 您在进行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关键字。 见下文:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM