javascript - Protobuf 编码返回空值
问题描述
我正在尝试使用 protobufjs 中的编码方法将消息编码到缓冲区。
这是我的代码。
setValue(value) {
var address = makeAddress(value);
let data = protobuf["Icao"].create({data:value})
let container = protobuf["IcaoContainer"].create()
container.entries = data
console.log(container)
var stateEntriesSend = {}
stateEntriesSend[address] = protobuf['IcaoContainer'].encode(container).finish();
console.log(stateEntriesSend[address])
return this.context.setState(stateEntriesSend, this.timeout).then(function(result) {
console.log("Success", result)
}).catch(function(error) {
console.error("Error", error)
})
}
的值 console.log(container)
低于,这是正确的。
IcaoContainer {
entries:
Icao {
data: <Buffer a2 66 61 63 74 69 6f 6e 63 73 65 74 64 64 61 74 61 68 61 73 61 70 6f 69 75 79> } }
但我正在尝试将其编码为缓冲区使用protobuf['IcaoContainer'].encode(container).finish()
它似乎返回一个空缓冲区。的值console.log(stateEntriesSend[address])
低于
<Buffer >
我的原型文件。
syntax = "proto3";
message Icao {
string data = 1;
}
message IcaoContainer {
repeated Icao entries = 1;
}
这里有什么问题?
解决方案
以防万一其他人遇到同样的问题,我已经弄清楚哪里出了问题。
根据我的 Icao 消息,我在我的原型中定义了数据应该是一个字符串。但是当我调用 setValue 方法时,我传递的是一个 JSON 对象而不是那个字符串值。所以当我使用
protobuf["Icao"].create({data:value})
该值不是字符串。这就是问题所在。根据protobufjs 文档,在使用 create 方法之前验证有效负载始终是一个好习惯。像这样。
// Exemplary payload
var payload = { awesomeField: "AwesomeString" };
// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
var errMsg = AwesomeMessage.verify(payload);
if (errMsg)
throw Error(errMsg);
// Create a new message
var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary
// Encode a message to an Uint8Array (browser) or Buffer (node)
var buffer = AwesomeMessage.encode(message).finish();
// ... do something with buffer
这给我一个错误,说数据必须是字符串。这就是问题所在。
而且因为我repeated
在 IcaoContainer 中使用了关键字,所以container.entries
应该是一个数组。
推荐阅读
- javascript - 我想根据价格和数量获得 3 件商品的总和
- javascript - 将 Sencha ExtJs 2.2.3 升级到版本 6
- php - 在 Laravel 的每个页面上使用代码的最佳实践
- php - Codeception 和 Selenium:无法设置 cookie
- python - mypy 没有检测到未初始化的属性
- html - 如果元素的文本内容太长,如何在布局网格中强制换行?
- kubernetes - 如何获取 Kubernetes 服务的集群 IP
- javascript - 将按钮属性中的文本复制到剪贴板
- perl - Encode::Guess:guess_encoding 在不同的上下文中给出不同的结果
- c# - Wpf 宽度绑定到带有星号的属性