简体   繁体   English

Output 数据从外部 API 在快速获取请求中获得

[英]Output data got from external API on express get request

From the example code on the gtfs-realtime-bindings library's documentaion ,从 gtfs-realtime-bindings 库的文档中的示例代码,
I tried to put similar logic inside my router but was not able to take the result out of request()我试图将类似的逻辑放在我的路由器中,但无法从 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"然后我尝试使用 axios,但decode()引发“错误:非法缓冲区”

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'.对于 axios 请求,尝试添加 responseType: 'arraybuffer'。 This worked for me for the same issue stated for "axios, but decode() raise 'Error: illegal buffer'"这对我来说适用于“axios,但解码()引发'错误:非法缓冲区'”的相同问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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