将 protobuf 对象返回为 json
returning protobuf object as json
我有一个 node-js 作为测试基础设施的一部分,它的行为类似于缓存,我们使用它来确保正确生成请求,我们发送给它的一种请求是 protobuf 请求,以验证发送的请求,我们将其存储在缓存对象中,然后根据 uri 我们检索它(使用 uri 作为键)。
var store = function(req,res) {
obj['body'] = req.body;
originalUrl = req.originalUrl;
cache.record(originalUrl, obj);
}
router.get('/cache', function (req, res) {
var key = req.query['originalUrl'];
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(cache.get(key)));
});
对于正常的 post/get 请求,这工作正常,但我无法获取二进制格式的 protobuf 请求,使用调试我可以看到它已添加到缓存中,但我不知道如何对于 return 它,最好的情况是 return 使用对象和模板的 json 演示文稿(如果该库已经存在),如果不可能 return字节,客户端可以将它们转换为 protobbuf
有一个 protobufjs
模块可以在 Node 中使用协议缓冲区:
I can't figure out how to return it, best case would be to return the json presentation using the object and the template if a library for that already exists
您可以使用 protobufjs
中的 Message.decode 解码缓冲区,如果需要,您将能够发送相同数据的 JSON 表示。
在以下位置有非常好的文档:
我有一个 node-js 作为测试基础设施的一部分,它的行为类似于缓存,我们使用它来确保正确生成请求,我们发送给它的一种请求是 protobuf 请求,以验证发送的请求,我们将其存储在缓存对象中,然后根据 uri 我们检索它(使用 uri 作为键)。
var store = function(req,res) {
obj['body'] = req.body;
originalUrl = req.originalUrl;
cache.record(originalUrl, obj);
}
router.get('/cache', function (req, res) {
var key = req.query['originalUrl'];
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(cache.get(key)));
});
对于正常的 post/get 请求,这工作正常,但我无法获取二进制格式的 protobuf 请求,使用调试我可以看到它已添加到缓存中,但我不知道如何对于 return 它,最好的情况是 return 使用对象和模板的 json 演示文稿(如果该库已经存在),如果不可能 return字节,客户端可以将它们转换为 protobbuf
有一个 protobufjs
模块可以在 Node 中使用协议缓冲区:
I can't figure out how to return it, best case would be to return the json presentation using the object and the template if a library for that already exists
您可以使用 protobufjs
中的 Message.decode 解码缓冲区,如果需要,您将能够发送相同数据的 JSON 表示。
在以下位置有非常好的文档: