我正在尝试使用 this 创建一个简单的 Notes CRUD API教程。该教程声称从客户端调用服务器(node get_notes.js
)中的List
方法应该返回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;
}
最佳答案
您的 NoteList
消息类型包含一个字段 notes
,它是 Note
消息的列表。要发送该类型的消息,您需要发送一个带有单个字段的对象,该字段是类似 Note
的对象列表。在本例中,应该如下所示:
const notes = { notes: [
{ id: '1', title: 'Note 1', content: 'Content 1'},
{ id: '2', title: 'Note 2', content: 'Content 2'}
]
}
关于node.js - 调用 gRPC 服务器不会在 Node 中返回预期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949908/