如 this issue 中所述,我们无法使用 Node 实现来实现 gRPC 客户端,因为“RN 不是纯 Node”。
所以我开始使用 Native Modules 进行 Objective-C 实现.
[service postWithRequest:request handler:^(RequestConfirmation * _Nullable response, NSError * _Nullable error) {
if (response) {
// This prints correctly in my JS console
RCTLogInfo(@"%@", response.message);
// This generates an error, see below
resolve(response);
// This works
NSDictionary *formattedResponse = @{
@"id": response.id_p,
@"message": response.message
};
resolve(formattedResponse);
} else {
reject(@"error", @"An error occurred while saving", error);
}
}];
错误:
RCTJSONStringify() encountered the following error: Invalid type in JSON write (RequestConfirmation)
如您所见,问题出在 resolve
方法上。我想 React 没有找到任何方法将我的原型(prototype)消息转换为 JSON。
如何保持响应不变并将其传递给 resolve 方法? 然后我可以在我的 JS 代码中对其进行解码。
谢谢。
编辑 1:
RequestConfirmation
在我的 proto
文件中定义如下:
message RequestConfirmation {
string id = 1;
string message = 2;
}
然后在 Objective-C 中生成:
@interface RequestConfirmation : GPBMessage
@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p;
@property(nonatomic, readwrite, copy, null_resettable) NSString *message;
@end
最佳答案
也许以下是一个潜在的解决方案。
- grpc-web - Typescript/Javascript、浏览器或 NodeJS!
除了不幸的命名之外,这似乎不是仅仅是the official, C++-using, grpc-web project的一个分支。 ).
引用 Improbable 项目自己的 grpc-web-client页:
This library is intended for both JavaScript and TypeScript usage from either a browser or Node.js
Improbable 版本的可能好处似乎是:
- 它似乎没有使用本地代码(即没有 C/C++/Java)
- 它可以为 Node.JS 生成 Typescript(因此是 JavaScript)
所以,也许,当第 2 点与 NodeJS-on-RN 项目(例如 rn-nodeify)相结合时,我们可以让 GRPC-on-RN 工作。 .
如果您对此有任何成功,请提供反馈。
关于node.js - 在 iOS React Native 应用程序中实现 gRPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44962290/