You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Android端使用react-native-sse无法连接SSE如何解决?

解决方案

你可以按以下步骤逐一调整排查:

  • 检查安卓网络权限配置
    打开android/app/src/main/AndroidManifest.xml,确认已添加网络权限,没有的话补充即可:
<uses-permission android:name="android.permission.INTERNET" />
  • 修改EventSource实例化配置
    安卓端默认会缓冲流式响应,且多数SSE服务端要求明确指定流式请求头,官方示例没有配置这些参数,修改后的代码如下:
import EventSource from "react-native-sse";

const es = new EventSource("https://your-sse-server.com/.well-known/mercure", {
  headers: {
    "Accept": "text/event-stream",
    "Cache-Control": "no-cache",
  },
  reactNative: {
    // 关闭安卓端流式响应缓冲,是解决该问题的核心配置
    disableBuffering: true
  },
  withCredentials: false
});

// 原有事件监听代码保持不变即可
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.");
});
  • 匹配服务端事件类型
    如果服务端推送时指定了自定义的event字段,不要只监听默认的message事件,需要添加对应事件名的监听逻辑。比如服务端推送事件类型为notice,就需要额外添加es.addEventListener('notice', callback)的监听。

  • 本地调试适配
    如果你是在内网环境调试,请求地址不要写localhost或者127.0.0.1,要替换为运行服务端的电脑的局域网IP,同时确保测试手机和电脑在同一局域网下,没有防火墙拦截请求。

  • 兼容版本适配
    如果上述配置都调整后仍有问题,可以尝试将react-native-sse降级到1.0.0版本,1.1.0版本在RN 0.65.x版本上存在已知的安卓端兼容性问题。

内容的提问来源于stack exchange,提问作者Lenny4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:45:00