Protobuf.js:作家似乎没有“完成”

Protobuf.js: the Writer doesn't seems to `finish`

我在 TypeScript 前端使用 Protobuf 时遇到了一个奇怪的错误。我正在使用 Axios 调用我的 REST API 和 protobuf.js 包来处理我前端的 Protobuf。我是protobuf的新手,这个问题可能源于我缺乏知识。

当我使用负载多次调用我的 API 时出现问题。

例如,我想要post 3 个对象:object_1object_2object_3。因此,我提出了三个 post 请求。第一个请求总是被正确处理——object_1 被添加到后端。然而,下面的postobject_2object_3又是postobject_1了。我调查了这个问题,发现我的 protobuf 已附加到有效负载中。这意味着我在第二个请求的有效负载中有 object_1object_2,在第三个请求的有效负载中有 object_1object_2object_3。我的 API 只读取第一个 protobuf,即 object_1 并添加三次 object_1.

我正在使用文档中所述的 protobuf.js 软件包:

const message = Message.create({ message: 'hello' });
const buffer = Message.encode(message).finish();
await axios.post([...] message [...]);

有人遇到过这个问题吗?我做错了什么?

谢谢!

protobufjs的Writer对象使用共享数组缓冲区

但是 axios post 不会查找 byteOffset 和 byteLength 属性,而是使用整个共享缓冲区,而不仅仅是您想要的字节。

您可以像这样提取相关字节:

const message = Message.create({ message: 'hello' });
const x = Message.encode(message).finish();
const buffer = new Uint8Array(x.buffer, x.byteOffset, x.byteLength);

在我看来,protobufjs 有点过时了。这是一个无耻的插件,因为我是作者,但是如果你对 protobufjs 不满意,请看看protobuf-ts。您可以像这样将您的消息编码为二进制文件:

const message = Message.create({ message: 'hello' });
const bytes: Uint8Array = Message.toBinary(message);

它还 supports Angular 与 auto-generated Twirp 客户端。