从 gRPC 调用中获取空响应

Getting empty response from gRPC call

我有一个简单的 gRPC 服务器和客户端。服务器和客户端工作正常(我假设因为我收到响应并且没有错误)。但是响应是空的,我不知道为什么。

这是原型message.proto

syntax = "proto3";

message Msg {
    int32 timeStamp = 1;
    string text = 2;
    string sender = 3;
}

message Empty {}

service MsgService{
    rpc AllMessages (Empty) returns (MsgList) {}
}

message MsgList {
    repeated Msg msgs = 1;
}

server.js

const grpc = require('@grpc/grpc-js');
const PROTO_PATH = "./message.proto";
const protoLoader = require('@grpc/proto-loader');

const options = {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
}

const packageDefinition = protoLoader.loadSync(PROTO_PATH, options);
const msgProto = grpc.loadPackageDefinition(packageDefinition);

const server = new grpc.Server();
let savedMessages = [
    { timeStamp: 1, text: "lorem", sender: "alex" },
    { timeStamp: 2, text: "ipsum", sender: "bob" },
    { timeStamp: 3, text: "dolor", sender: "alex" },
    { timeStamp: 4, text: "net", sender: "bob" }
];

server.addService(msgProto.MsgService.service, {
    AllMessages: (_, callback) => {
        callback(null, savedMessages);
    }
})

server.bindAsync("127.0.0.1:50051", grpc.ServerCredentials.createInsecure(), (err, port) => {
    if (err) {
        console.log(err);
    }
    console.log(port);
    server.start();
    console.log("Server running at 127.0.0.1:50051");
})

client.js

const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = "./message.proto";

const options = {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true,
};

var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);

const MsgService = grpc.loadPackageDefinition(packageDefinition).MsgService;

const client = new MsgService(
    "localhost:50051",
    grpc.credentials.createInsecure()
);

client.AllMessages({}, (err, msg) => {
    // console.log(err);
    if (err) throw err;
    console.log(msg);
    // console.log(msg);
})

以及我得到的回复

{ msgs: [] }

如果有帮助,我正在关注此博客 post https://daily.dev/blog/build-a-grpc-service-in-nodejs

提前致谢。

您的 MsgList 消息定义是一条消息,其中包含一个名为 msgs 的字段,类型为 repeated Msg。您发送的对象应该具有该形式。因此,它应该是一个具有名为 msgs 的单个字段的对象,该对象具有与 Msg 消息定义的格式匹配的对象数组。你的 savedMessages 变量不是那个,它只是一个数组,这就是为什么发送它没有得到你想要的结果。