Angular 5 HttpClient 发布原始二进制数据

标签 angular typescript protocol-buffers

我的 WebApp 需要通过 ProtBuf 与我的服务器通信。为此,我需要能够发布原始二进制数据。

这是我现在使用的代码。问题在于 HttpClient 将 Uint8Array 编码为 JSON 数组,因此结果不再是有效的 protobuffer:

const message = LoginRequest.fromObject({
  code: code,
  username: username,
  password: password
});

const buffer: Uint8Array = LoginRequest.encode(message).finish();

this.http.post('https://api.myserver.com', buffer)
  .subscribe(/*...*/);

HttpClient.post接受一些选项,你可以设置responseTypejson, text, blobarraybuffer。但这只是设置了预期的响应类型,请求的主体仍然被编码为 JSON。

HttpClient 是否可以发送未编码的正文?

编辑:这是我在服务器上收到的正文:

{"0":10,"1":3,"2":97,"3":98,"4":99,"5":18,"6":5,"7":97,"8":100,"9":109,"10":105,"11":110,"12":26,"13":8,"14":112,"15":97,"16":115,"17":115,"18":119,"19":111,"20":114,"21":100}

最佳答案

reference中可以看出,请求body的类型是any,这表明它是自由格式的。 HttpClient使用HttpRequest表示请求,它使用serializeBody method转换请求体:

Transform the free-form body into a serialized format suitable for transmission to the server.

它接受多种主体类型,所有主体类型都相应地进行了字符串化。原始主体应为 BlobArrayBuffer 或字符串。所以Uint8Array应该转换为其中之一,例如:

const arr: Uint8Array = LoginRequest.encode(message).finish();
const buffer: ArrayBuffer = arr.buffer;

关于Angular 5 HttpClient 发布原始二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354712/

相关文章:

node.js - Angular 5 插件依赖项

c++ - Protobuf ld undefined symbol ~InternalMetadata()

angular - MockBackend 和 HttpTestingController 有什么区别?

angular - 如何更新 FormArray 的控件

angular - 如何在 guard angular 2 中获取请求 url

javascript - TypeScript:在 Enum 上执行 switch-case 来设置变量的惯用方法

javascript - Mongodb:如何通过我的 api 填充我的模式中引用的模式

reactjs - 在带有 TypeScript 的 next.js 中使用 Router 的空安全方法

c++ - 如何克服 Boost Spirit AST 困惑

python - 如何将 Google-Cloud-Vision OCR protobuf 响应保存/加载到磁盘?