React Native 无法在 android 中连接到 SSE

React native can't connect to SSE in android

我正在使用包: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.");
});

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

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

in the reactNativeFlipper.java, the following lines making EventSource (SSE) not working.

解决方案 1:

  • 转到android/app/src/debug/java/com/iwaiterapp/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

这个错误只发生在调试中,所以而不是 运行ning:

  • 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"
  },
  // ...
}

就我而言,我无法关闭事件源。 es.addEventListener("关闭")