【问题标题】:calling gRPC server doesn't return expected data in Node调用 gRPC 服务器不会在 Node 中返回预期的数据
【发布时间】:2019-09-16 03:03:51
【问题描述】:

我正在尝试使用 this 教程创建一个简单的 Notes CRUD API。该教程声称从客户端调用服务器中的List 方法(node get_notes.js)应该返回notes 数组,但我总是得到一个空对象。

server.js

const grpc = require('grpc')
const protoLoader = require('@grpc/proto-loader')
const packageDefinition = protoLoader.loadSync('notes.proto');
const notesProto = grpc.loadPackageDefinition(packageDefinition);

const notes = [
    { id: '1', title: 'Note 1', content: 'Content 1'},
    { id: '2', title: 'Note 2', content: 'Content 2'}
]

const server = new grpc.Server()

server.addService(notesProto.NoteService.service, {
    list: (_, callback) => {
        callback(null, notes)
    },
})

server.bind('127.0.0.1:50051', grpc.ServerCredentials.createInsecure())
console.log('Server running at http://127.0.0.1:50051')
server.start()

client.js

const grpc = require('grpc')
const protoLoader = require('@grpc/proto-loader')

const packageDefinition = protoLoader.loadSync('notes.proto');
const notesProto = grpc.loadPackageDefinition(packageDefinition);

const NoteService = notesProto.NoteService

const client = new NoteService('localhost:50051',
    grpc.credentials.createInsecure())
module.exports = client

get_notes.js

const client = require('./client')
client.list({}, (error, notes) => {
    if (!error) {
        console.log('successfully fetch List notes')
        console.log(notes)
    } else {
        console.error(error)
    }
})

notes.proto

syntax = "proto3";

service NoteService {
    rpc List (Empty) returns (NoteList) {}
}
message Empty {}

message Note {
    string id = 1;
    string title = 2;
    string content = 3;
}

message NoteList {
   repeated Note notes = 1;
}

【问题讨论】:

    标签: node.js grpc


    【解决方案1】:

    您的NoteList 消息类型包含一个字段notes,它是Note 消息的列表。要发送该类型的消息,您需要发送一个具有单个字段的对象,该字段是Note-like 对象的列表。在这种情况下,应该如下所示:

    const notes = { notes: [
        { id: '1', title: 'Note 1', content: 'Content 1'},
        { id: '2', title: 'Note 2', content: 'Content 2'}
      ]
    }
    

    【讨论】:

    • 感谢您的回答。它起作用了,但是有没有办法发送那个原始对象?我应该如何优化.proto文件中的消息格式以发送原始对象?
    • 这是发送对象数组的最佳方式。一种可能的替代方法是使用响应流,并将数组的每个元素作为单独的响应消息发送。如果不是所有的响应数据都立即可用,这将主要是有用的。
    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 2022-11-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多