gpt4 book ai didi

javascript - 从 node.js 向 WMATA API 发出 get 请求

转载 作者:行者123 更新时间:2023-12-02 23:23:58 24 4
gpt4 key购买 nike

当我从 Node 服务器对 WMATA API 进行 GET 调用时,收到 400 响应代码。

这是 API 文档:https://developer.wmata.com/docs/services/5476365e031f590f38092508/operations/5476365e031f5909e4fe331d

最初我使用的是 https:

const https = require('https');
var wmataBusTimesURL = 'https://api.wmata.com/NextBusService.svc/json/jPredictions'
+ '?StopID='
+ stopID
+ theConfig.wmata_api_key;
if (!this.stopUpdates) {
// make the async call
https.get(wmataBusTimesURL, (res) => {
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
// once you have all the data send it to be parsed
self.parseBusTimes(theConfig, stopID, JSON.parse(rawData), busStopList);
});
})
// if an error handle it
.on('error', (e) => {
self.processError();
}); }

但我很确定我没有正确传递 API key 。

然后我尝试使用请求:

var request = require('request');
// build the full URL call
request({
url: 'https://api.wmata.com/NextBusService.svc/json/jPredictions',
method: 'GET',
headers: {
'api_key': theConfig.wmata_api_key,
'StopID': stopID
},
}, function (error, response, body) {

if (!error && response.statusCode == 200) {
self.sendSocketNotification("DEBUG", body);
}
else {
self.sendSocketNotification("DEBUG", "In updateBusTimes request with status code: " + response.statusCode);
}
});

现在我收到了 400 条回复。对一种或两种方法有帮助吗?文档推荐ajax,但我对此不熟悉。基本上只要我能成功调用,我对任何方法都持开放态度。

最佳答案

API key 应位于请求 header 中。将您的代码更改为:

const https = require('https');

var params = {
hostname: 'api.wmata.com',
port: 443,
path: '/NextBusService.svc/json/jPredictions' + '?StopID=' + stopID,
method: 'GET',
headers: {
api_key: theConfig.wmata_api_key
}
};

if (!this.stopUpdates) {
// Make the async call.
https.get(params, res => {
let rawData = '';
res.on('data', chunk => rawData += chunk);
// Once you have all the data, send it to be parsed.
res.on('end', () => self.parseBusTimes(theConfig, stopID, JSON.parse(rawData), busStopList));
})
// If an error occurs, handle it.
.on('error', e => self.processError());
}

关于javascript - 从 node.js 向 WMATA API 发出 get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56820626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com