React Native无法连接到Android中的SSE

2023-12-07

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

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


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

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

解决方案一:

  • go to 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"
  },
  // ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native无法连接到Android中的SSE 的相关文章

随机推荐