从Axios API返回数据 [英] Returning data from Axios API

查看:456
本文介绍了从Axios API返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use a Node.JS application to make and receive API requests. It does a get request to another server using Axios with data it receives from an API call it receives. The second snippet is when the script returns the data from the call in. It will actually take it and write to the console, but it won't send it back in the second 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,这对我的情况没有帮助.

I'm aware this is wrong, I'm just trying to find a way to make it work. The only way I can seem to get data out of it is through console.log, which isn't helpful in my situation.

推荐答案

axiosTest函数中的axios调用返回promise,然后在使用另一个.then

Return the promise from the axios call in the axiosTest function, then get the value out of the promise when calling it using another .then

function axiosTest() {
  return axios.get(url).then(response => {
    // returning the data here allows the caller to get it through another .then(...)
    return response.data
  })
}

axiosTest().then(data => {
  response.json({ message: 'Request received!', data })
})

我还建议您阅读有关承诺如何工作的更多信息: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises

I'd also recommend reading up more on how promises work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

这篇关于从Axios API返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆