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

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

问题描述

我正在尝试使用 Node.JS 应用程序来发出和接收 API 请求.它使用 Axios 向另一台服务器发出 get 请求,并使用从它接收的 API 调用中接收到的数据.第二个片段是脚本从调用中返回数据的时间.它实际上会接收它并写入控制台,但不会在第二个 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() 函数没有返回承诺.为了清楚起见,这里有一个扩展解释:

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

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
}

  • promises 使用指南
  • 异步函数信息

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

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