【问题标题】:Making a get request to the WMATA API from node.js从 node.js 向 WMATA API 发出 get 请求
【发布时间】:2019-11-11 05:20:00
【问题描述】:

当我从节点服务器对 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 密钥。

然后我尝试使用请求:

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,但我对此并不熟悉。基本上,只要我能成功拨打电话,我对任何方法都持开放态度。

【问题讨论】:

  • 返回文档并非常仔细地查看请求的要求。 400 状态代码告诉您您的请求无效。只需找到并解决该问题。那么,顺便说一句,以上两种方法都可以。
  • 我已经查看了它们,但我无法弄清楚。这就是我寻求帮助的原因...
  • @devio 刚刚回答的内容。打败我吧! :-)

标签: javascript node.js https get request


【解决方案1】:

API 密钥应位于请求标头中。将您的代码更改为:

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

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 2019-08-10
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多