繁体   English   中英

如何使用JavaScript从实时输出流中获取数据

[英]How to fetch data from a live outputstream with JavaScript

实时输出流链接: https ://wunder-provider.herokuapp.com/

我上面有一个实时输出流,该流每3到15秒生成一次随机用户信息。 我正在创建一个React Native应用程序,该应用程序将这些用户及其信息显示在屏幕上。

我的问题是从该输出流中获取数据。

当我尝试fetch方法时,它将返回此错误。

  componentWillMount() {
    fetch("https://wunder-provider.herokuapp.com/")
      .then(res => res.json())
      .then(res => console.log(JSON.stringify(res)))
  }

错误:

Possible Unhandled Promise Rejection (id: 0):
SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected token < in JSON at position 0
    at parse (<anonymous>)
    at tryCallOne (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:3747:14)
    at blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:3848:17
    at blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:28372:21
    at _callTimer (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:28261:9)
    at _callImmediatesPass (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:28297:9)
    at Object.callImmediates (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:28516:14)
    at MessageQueue.__callImmediates (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:3149:16)
    at blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:2970:18
    at MessageQueue.__guard (blob:http://localhost:19001/6cf08556-7310-4c2d-b838-9a8fcadc2be1:3132:13)

如何从该来源获取数据并添加到我的状态?

解决了!

  constructor(props) {
    super(props);

    this.state = {
      users: []
    };

    const ws = new WebSocket(
      "wss://wunder-provider.herokuapp.com/socket.io/?EIO=3&transport=websocket"
    );

    ws.onopen = () => {
      console.log("Opened.");
    };

    ws.onmessage = msg => {
      if (msg.data.substr(0, 2) === "42") {
        const stringToBeParsed = msg.data.substr(2);
        const obj = JSON.parse(stringToBeParsed);
        this.setState({ users: [...this.state.users, obj[1].results[0]] });
      }
    };
  }

您正在尝试将HTML解析为JSON。 您所请求的网址正在提供HTML页面。 您可以通过添加console.log(res)来验证。 输出将是HTML。

Unexpected token <错误是<html>标记

发布的答案表明您正在尝试将HTML解析为JSON是正确的。 如果您在“ https://wunder-provider.herokuapp.com/ ”中打开“开发人员工具”并打开“网络”标签,则可以看到请求。

这些请求之一https://wunder-provider.herokuapp.com/以HTML作为其响应主体。 这意味着当您对这个URL执行获取功能时,您将收到HTML。

此外,如果我们仔细研究这些请求,那么您会特别感兴趣,这就是对wss://wunder-provider.herokuapp.com/ URL的请求。 您可以做的是在React Native应用程序和服务器之间创建一个websocket连接,并订阅“ userList”通道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM