Выполнение запроса get к API-интерфейсу WMATA из node.js - PullRequest
0 голосов
/ 29 июня 2019

Я получаю код ответа 400, когда я выполняю вызов GET для API WMATA с сервера узла.

Вот документация 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, но я не знаком с этим.По сути, я открыт для любого метода, если могу успешно выполнить вызов.

1 Ответ

1 голос
/ 29 июня 2019

Ключ 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());
}
...