简体   繁体   English

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

[英]How I can send my axios response to a variable with node.js

In fact, I begin with node.js.事实上,我从 node.js 开始。 And i don't know how to pass the response to a variable.而且我不知道如何将响应传递给变量。 I don't want to make my code in my "response".. I try a lot of things but nothing is working.. I know is a simple question.. but it's not working我不想在我的“响应”中制作我的代码..我尝试了很多东西,但没有任何效果..我知道这是一个简单的问题..但它不起作用

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)

You should use promises and wait for the response to be ready:您应该使用承诺并等待响应准备就绪:

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);
});

Or, using async/await:或者,使用异步/等待:

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

consoleLeagues();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解压缩文件并在 Node.js 中发送响应? - How can I ungzip a file and send it in response in Node.js? 使用流将响应通过管道传输到变量中 | 爱讯 | 节点.js - Piping the response into a variable using streams | Axios | Node.js 我在 Node.js API 上使用 Axios 没有收到 GET 请求的响应 - I'm getting no response of GET request with Axios on my Node.js API 如何在Node.js中发送响应 - How to send response in Node.js 如何从我的 Node.JS 向我的 Javascript 客户端发送一个警报? - How can I send one alert from my Node.JS to my Javascript client? 如何在 node.js 中下载带有 Axios 的文件并写入响应 - How to download file with Axios in node.js and write to the response 如何从服务器向其他客户端发送请求并接收客户端的响应,然后在 node.js 中发送数据? - How can I send request from server to other clients and receive response from clients and then send data in node.js? 如何声明我以后可以在我的 js 文件中使用的 node.js 变量? - How to declare a node.js variable that i can later use in my js file? 每当在我的 Node.js API 中发出 GET 请求时,我如何发送随机集合? - How can i send a random collection whenever a GET request made in my Node.js API? node.js将变量的响应发送到浏览器,而不是控制台 - node.js express send response from variable to the browser and not the console
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM