javascript – Protobuf:WebApi – > JS – 解码对象为空

前端之家收集整理的这篇文章主要介绍了javascript – Protobuf:WebApi – > JS – 解码对象为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过Ajax请求从WebApi控制器向 Html页面发送一个对象.

当我在JS中收到对象时,它是空的.但是服务器端的对象不是空的,因为当我查看byte []时,它的长度大于0.

>服务器端,我使用的是dll provided by Google.
> JS方面,我使用的是ProtobufJS library.这是我的.proto文件

  1. Syntax="proto3";
  2.  
  3. message Container {
  4. repeated TestModel2 Models = 1;
  5. }
  6.  
  7. message TestModel2 {
  8. string Property1 = 1;
  9. bool Property2 = 2;
  10. double Property3 = 3;
  11. }

>服务器代码

  1. var container = new Container();
  2.  
  3. var model = new TestModel2
  4. {
  5. Property1 = "Test",Property2 = true,Property3 = 3.14
  6. };

container.Models.Add(模型);
> Base64数据:

ChEKBFRlc3QQARkfhetRuB4JQA==

> JS解码:

  1. var ProtoBuf = dcodeIO.ProtoBuf;
  2. var xhr = ProtoBuf.Util.XHR();
  3. xhr.open(
  4. /* method */ "GET",/* file */ "/XXXX/Protobuf/GetProtoData",/* async */ true
  5. );
  6. xhr.responseType = "arraybuffer";
  7. xhr.onload = function (evt) {
  8. var testModelBuilder = ProtoBuf.loadProtoFile(
  9. "URL_TO_PROTO_FILE","Container.proto").build("Container");
  10. var msg = testModelBuilder.decode64(xhr.response);
  11. console.log(JSON.stringify(msg,null,4)); // Correctly decoded
  12. }
  13. xhr.send(null);

> JS控制台中的结果对象:

  1. {
  2. "Models": []
  3. }

> bytebuffer.js
> protobuf.js v5.0.1

解决方法

最后我自己解决了这个问题.

这是客户端的错误.

>实际上xhr.response是JSON格式,所以它在双引号“ChEKBFRlc3QQARkfhetRuB4JQA ==”之间.我不得不在这里JSON.parse我的response.enter代码
>我删除了xhr.responseType =“arraybuffer”;

这是我现在的代码

  1. var ProtoBuf = dcodeIO.ProtoBuf;
  2. var xhr = ProtoBuf.Util.XHR();
  3. xhr.open(
  4. /* method */ "GET",/* async */ true
  5. );
  6. // xhr.responseType = "arraybuffer"; <--- Removed
  7. xhr.onload = function (evt) {
  8. var testModelBuilder = ProtoBuf.loadProtoFile(
  9. "URL_TO_PROTO_FILE","Container.proto").build("Container");
  10. var msg = testModelBuilder.decode64(JSON.parse(xhr.response)); <-- Parse the response in JSON format
  11. console.log(msg); // Correctly decoded
  12. }
  13. xhr.send(null);

猜你在找的JavaScript相关文章