【问题标题】:How to listen to server side events in React Native?如何在 React Native 中监听服务器端事件?
【发布时间】:2019-06-18 17:50:43
【问题描述】:

我正在通过 react-native-event-source 库在我的 Expo React Native App 上设置服务器发送的事件。

使用下面的函数,我应该每 10 秒记录一次 data。但是控制台中没有打印任何内容。我错过了什么吗?

  getTodayMissions() {
    ...
    const options = { headers: { Authorization: `Bearer ${token}` } };
    const eventsurl = `${BASE_URL}/server-events/`;
    const eventSource = new RNEventSource(eventsurl, options);
    const url = `missionstodayapp?userId=${user.id}`;


    console.log('start the watch', eventsurl, url);
    this.eventSource.addEventListener(url, (data) => {
      console.log('started the watch', data);
    });
  }

【问题讨论】:

    标签: react-native expo server-sent-events


    【解决方案1】:

    如果您使用的是 android studio 模拟器,您应该使用 10.0.0.2 而不是 localhost127.0.0.1 作为您的基本 URL。

    【讨论】:

    • 我终于成功地让它工作了。我必须在 addEventListener 方法中指定事件名称,如下所示:this.eventSource.addEventListener('myEventName', (data) => { console.log('started the watch', data); });
    • “myEventName”应该是什么?我在浏览器中使用“消息”,但这似乎在这里不起作用。 @ceessay
    • 在浏览器中尝试使用“onmessage”方法而不是“addEventListener”,如下所示: const eventSource = new EventSource(yourURL); eventSource.onmessage = e => { console.log(e)}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2018-04-30
    • 1970-01-01
    • 2015-05-23
    • 2018-09-24
    • 1970-01-01
    • 2022-07-07
    相关资源
    最近更新 更多