前端项目引入protobufjs编码返回空二进制

112 阅读1分钟
  • 背景:学习protobufjs编码解码时,发现message有数据,但是encode编码出来的结果却是空的二进制。 image.png

protobuf使用是按照官网给的案例实现

给出官网 www.npmjs.com/package/pro…

protobuf使用代码如下 image.png

仔细对比官网案例,发现是变量名称问题。官方推荐使用驼峰命名法,而我的是下划线,导致.proto文件内容字段不匹配,引发了二进制解码为空的结果。

遂修正如下:

        const shoeAIGCMsgMessage = ShoeAIGCMsg.create({
            loopback: null,
            error: null,
            shoeAigcReq: shoeAIGCReqMessage,
            shoeAigcRsp: null
        });
        console.log('ShoeAIGCMsg Message:', shoeAIGCMsgMessage);  // 查看整个消息对象

        // 对ShoeAIGCMsg消息对象进行编码(如果需要发送请求等场景会用到编码后的二进制数据)
        shoeAIGCMsgMessage.shoeAigcReq.prompt = '紫色'
        const encodedData = ShoeAIGCMsg.encode(shoeAIGCMsgMessage).finish();

运行后结果也正确了。 image.png

完。