javascript - 如何使用 node.js 将 axios 响应发送到变量

标签 javascript node.js axios

事实上,我是从 Node.js 开始的。而且我不知道如何将响应传递给变量。我不想在我的“响应”中编写我的代码..我尝试了很多事情,但没有任何效果..我知道这是一个简单的问题..但它不起作用

const axios = require('axios');
var test = null
function getLeagues () {
  axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
   headers: {
    'X-RapidAPI-Key': '<my-api-key>'
   }
  })
  .then(response => {

    test = response.data.api.fixtures

    return response.data.api.fixtures
  })
  .catch(error => {
    console.log(error);
  });
}

console.log(test)

最佳答案

您应该使用 promise 并等待响应准备好:

const axios = require('axios');

function getLeagues () {
  return axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
   headers: {
    'X-RapidAPI-Key': 'foo-api-key'
   }
  })
  .then(response => {
    return response.data.api.fixtures
  })
  .catch(error => {
    console.log(error);
    return Promise.reject(error);
  });
}

getLeagues().then(response => {
  console.log(response);
});

或者,使用异步/等待:

const consoleLeagues = async () => {
  const leagues = await getLeagues();
  console.log(leagues);
};

consoleLeagues();

关于javascript - 如何使用 node.js 将 axios 响应发送到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59397832/

相关文章:

javascript - 使用 javascript 后 css 悬停事件不起作用?

javascript - 使用 javascript Onclick 将数据传递到数据库

javascript - 在超时 Node.js 中从数组中删除元素

node.js - Google 搜索控制台 API,google.webmasters.searchanalytics.query "startDate field is required"

ecmascript-6 - 如何使用axios序列化参数

javascript - 如何使用 Highcharts 在 xAxis 上仅显示工作日?

javascript - 正则表达式有问题!

Mysql 返回一个不正确的 bigint 结果,非常奇怪的错误

node.js - Node 服务器无法检索react axios请求头参数的值

javascript - JavaScript Axios 中的 NeSTLed API 调用,返回正确的 promise