[英]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.