快速获取请求时从外部 API 获取的输出数据

问题描述

来自 gtfs-realtime-bindings 库 documentaion 上的示例代码
我试图将类似的逻辑放在我的路由器中,但无法从 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

然后我尝试使用 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('/',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) **/

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)