React Native无法连接到Android中的SSE

Ale*_*122 2 react-native

我正在使用该包: 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.");
});
Run Code Online (Sandbox Code Playgroud)
  • 反应本机:v0.65.1
  • 反应本机-sse:v1.1.0

我怎样才能让它发挥作用?

Ale*_*122 8

这就是原因: https: //github.com/facebook/flipper/issues/2495

在reactNativeFlipper.java中,以下行使EventSource(SSE)不起作用。

解决方案一:

  • 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();
Run Code Online (Sandbox Code Playgroud)

解决方案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"
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)