简体   繁体   中英

Output data got from external API on express get request

From the example code on the gtfs-realtime-bindings library's documentaion ,
I tried to put similar logic inside my router but was not able to take the result out of request()

route.get('/', (req, res) => {
  const data = [];
  request(requestSettings, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(body);
      feed.entity.forEach(function(entity) {
        if (entity.tripUpdate) {
          data.push(entity.tripUpdate);
        }
      });
    }
  res.status(200).json( data );
}); // empty array returns

Then I tried to use axios, but decode() raise "Error: illegal buffer"

const realtimeRequest = () => {
  axios.get('https://opendata.hamilton.ca/GTFS-RT/GTFS_TripUpdates.pb')
  .then(function (body) {
    const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(body.data);
    // body.data looks like this '\x03436\x12\x041219 ����\x06'
    return feed;
  }).catch(error => console.log(error));
}

route.get('/', (req, res) => {
  realtimeRequest()
  .then(() => {
    res.status(200).json( data );
  })
}
/**
Error: illegal buffer
    at create_typed_array (/node_modules/protobufjs/src/reader.js:47:15)
    at create_buffer (/node_modules/protobufjs/src/reader.js:69:19)
    at Function.create_buffer_setup (/node_modules/protobufjs/src/reader.js:70:11)
    at Function.decode (/node_modules/gtfs-realtime-bindings/gtfs-realtime.js:134:34) **/

For the axios request, try adding responseType: 'arraybuffer'. This worked for me for the same issue stated for "axios, but decode() raise 'Error: illegal buffer'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM