javascript 如何使用typescript解码通过axios获得的protobuf

xxls0lw8  于 2023-05-12  发布在  Java
关注(0)|答案(1)|浏览(283)

我是一个打字新手,我正在尝试理解如何使用axios下载实时gtfs数据(protobuf格式)。我得到一个非法的缓冲区错误,当我试图运行这段代码。我已经在下面完整地发布了错误。

import axios from "axios";
import * as GtfsRealtimeBindings from "gtfs-realtime-bindings";

const url = "https://www.rtd-denver.com/files/gtfs-rt/TripUpdate.pb";
export type RealtimeGtfsUrl = string;

export async function decodeRealtimeGtfs(
  url: RealtimeGtfsUrl,
): Promise<GtfsRealtimeBindings.transit_realtime.FeedMessage> {
  return await axios.get(url).then((response) => {
    return GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
      response.data,
    );
  });
}

const result = decodeRealtimeGtfs(url);

/Users/.../playground/node_modules/protobufjs/src/reader.js:47 throw Error(“非法缓冲区”);^
错误:create_typed_array(/Users/.../playground/node_modules/protobufjs/src/reader.js:四十七:15)at create_buffer(/Users/.../playground/node_modules/protobufjs/src/reader.js:六十三:(23)功能。create_buffer_setup(/Users/.../playground/node_modules/protobufjs/src/reader.js:六十四:(15)功能。decode(/Users/.../playground/node_modules/gtfs-realtime-bindings/gtfs-realtime。js:一百三十四:34)at /Users/.../playground/test.cjs:四十八:82在过程中processTicksAndRejections(节点:internal/process/task_queues:九十五:(五)

neekobn8

neekobn81#

响应为二进制格式,Axios默认为JSON /纯文本。
解码器期望ArrayBuffer,所以您需要做的就是告诉Axios期望的响应类型。
另外,不要将await.then()混合;只会让代码变得混乱。

export async function decodeRealtimeGtfs(
  url: RealtimeGtfsUrl,
): Promise<GtfsRealtimeBindings.transit_realtime.FeedMessage> {
  const { data } = await axios.get(url, { responseType: "arraybuffer" });
  return GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(data);
}

相关问题