首页 > 解决方案 > 如何使用内容类型 ='application/x-protobuf' 在 node.js 中发布数据

问题描述

我在使用 content-type='application/x-protobuf' 发布数据时遇到问题。我们可以从 HTTP 请求中请求 protobuf 吗?如果可以怎么办?

标签: node.jsprotocol-buffersproto

解决方案


如果您对 protobuffer 进行编码和解码,这将只是另一个常规请求。

最好的选择是使用这样的库进行编码和解码。

这是一个带有 proto 缓冲区的简单 axios 请求。

  const protobuf = require('protobufjs');

  ...

  const root = await protobuf.load('user.proto');  
  const User = root.lookupType('userpackage.User');

  const postBody = User.encode({ name: 'Joe', age: 27 }).finish();

  await axios.post('http://someaddress', postBody,  {
           headers: {
           'content-type': 'application/x-protobuf'
  }}).
  then(res => res.data);

推荐阅读