从 Axios API 返回数据

新手上路,请多包涵

我正在尝试使用 Node.JS 应用程序来发出和接收 API 请求。它使用 Axios 向另一台服务器发出 get 请求,其中包含从 API 调用接收到的数据。第二个片段是脚本从调用中返回数据的时候。它实际上会将数据写入控制台,但不会在第二个 API 中将其发送回。

function axiosTest() {
    axios.get(url)
        .then(function (response) {
            console.log(response.data);
            // I need this data here ^^
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
}

axiosTestResult = axiosTest();
response.json({message: "Request received!", data: axiosTestResult});

我知道这是错误的,我只是想找到一种方法让它发挥作用。我似乎可以从中获取数据的唯一方法是通过 console.log,这对我的情况没有帮助。

原文由 bunkerguy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 856
2 个回答

问题是原始 axiosTest() 函数没有返回承诺。为了清楚起见,这是一个扩展的解释:

 function axiosTest() {
 // create a promise for the axios request
 const promise = axios.get(url)

 // using .then, create a new promise which extracts the data
 const dataPromise = promise.then((response) => response.data)

 // return it
 return dataPromise
 }

 // now we can use that data from the outside!
 axiosTest()
 .then(data => {
 response.json({ message: 'Request received!', data })
 })
 .catch(err => console.log(err))

该函数可以写得更简洁:

 function axiosTest() {
 return axios.get(url).then(response => response.data)
 }

或者使用异步/等待:

 async function axiosTest() {
 const response = await axios.get(url)
 return response.data
 }

原文由 kingdaro 发布,翻译遵循 CC BY-SA 4.0 许可协议

我知道这篇文章很旧。但是我已经看到有人尝试使用 async 和 await 来回答问题,但都弄错了。这应该为任何新参考清除它

更新:2022 年 5 月 这个答案仍然很有趣,并且已将其更新为使用箭头函数

const axiosTest = async () {
      try {
        const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
        return response
      }

      catch (error) {
        console.log(error);
      }
    }

原文由 Muteshi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题