【发布时间】:2018-10-22 20:36:00
【问题描述】:
我正在尝试制作一个与此 jQuery 等效的 get 请求:
$.ajax({
headers: { 'X-Auth-Token': 'YOUR_API_KEY' },
url: 'http://api.football-data.org/v2/competitions/BL1/standings',
dataType: 'json',
type: 'GET',
}).done(function(response) {
console.log(response);
});
但是,我还没有弄清楚如何使用 nodejs - express。此代码来自附加到主应用程序的 api 路由模块。 该请求似乎有效,收集数据但并未结束。另外,从浏览器检查时,我看不到请求中的自定义标头。
app.get('/api/:league', function(req, res, next) {
var apiKey = process.env.API_KEY;
let url = 'api.football-data.org';
var options = {
host: url,
method: 'GET',
path: 'v2/competitions/BL1/standings',
headers: {
'X-Auth-Token': apiKey
}
};
let data = "";
var getReq = http.request(options,function(resp){
console.log("Connected");
resp.on("data", chunk => {
data += chunk;
});
resp.on("end", () => {
console.log("data collected");
});
});
getReq.on("error", (err) => console.log("OOPS!", err));
getReq.end(JSON.stringify(data));
})
【问题讨论】: