React native 无法在 android 中连接到 SSE



我正在使用的软件包:https://www.npmjs.com/package/react-native-sse

我不能管理从android服务器接收事件,即使我从文档中复制粘贴代码。

import EventSource from "react-native-sse";
const es = new EventSource("https://your-sse-server.com/.well-known/mercure");
es.addEventListener("open", (event) => {
console.log("Open SSE connection.");
});
es.addEventListener("message", (event) => {
console.log("New message event:", event.data);
});
es.addEventListener("error", (event) => {
if (event.type === "error") {
console.error("Connection error:", event.message);
} else if (event.type === "exception") {
console.error("Error:", event.message, event.error);
}
});
es.addEventListener("close", (event) => {
console.log("Close SSE connection.");
});
  • react-native: v0.65.1
  • react-native-sse: v1.1.0

我怎样才能使它工作?

原因如下:https://github.com/facebook/flipper/issues/2495

在reactNativeFlipper.java中,下面的行使EventSource (SSE)不工作。

解决方案1:

  • 转到android/app/src/debug/java/com/<projectname>/ReactNativeFlipper.java
  • 注释NetworkFlipperPlugin:
client.addPlugin(CrashReporterPlugin.getInstance());
// todo commented because of this issue https://github.com/binaryminds/react-native-sse/issues/3 https://github.com/facebook/flipper/issues/2495
//       NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
//       NetworkingModule.setCustomClientBuilder(
//           new NetworkingModule.CustomClientBuilder() {
//             @Override
//             public void apply(OkHttpClient.Builder builder) {
//               builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
//             }
//           });
//       client.addPlugin(networkFlipperPlugin);
client.start();

解决方案2:

如果您不想注释NetworkFlipperPlugin.

这个错误只在调试时发生,所以不要运行:

  • react-native run-android你必须运行:
  • react-native run-android --variant=release或者简单地在你的package.json
  • 中更改它
{
// ...
"scripts": {
"android": "react-native run-android --variant=release", // here
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
// ...
}

最新更新