如何将 axios get 请求的响应以 json 形式存储在 node.js 中?

问题描述 投票:0回答:1

我正在尝试使用 axios 向 api 发送请求并将 json 响应存储在变量中。当我将响应输出到控制台时,它会显示它,但是当设置等于它的变量并返回所述变量时,我只得到 Promise { } 作为输出。

const { default: axios } = require("axios");

async function getAvgPrice() {
    var data = []; // or whatever we would have to declare for a json object
    await axios.get("https://api.com/example.json")
    .then(function(res) {
        console.log(res); // <-- This outputs the correct response to console
        data.push(res);   // <-- This just doesn't do anything
    });
    return data;
}

var x = getAvgPrice();
console.log(x); // <-- (Output: Promise { <pending> })

我尝试向 api 发送请求并将响应存储为 json,但只能返回一个承诺。

javascript node.js json axios
1个回答
0
投票

您需要等待 getAvgPrice();因为它是一个异步函数。 因此

const x = await getAvgPrice();
将会起作用并为您提供实际数据。

© www.soinside.com 2019 - 2024. All rights reserved.