Websocket服务器和npm在本地主机上启动

时间:2020-05-01 18:59:23

标签: javascript node.js reactjs websocket

出于无聊,我目前尝试在本地主机上创建一个简单的聊天应用。

首先,我从基于create-react-app的简单React应用开始。 在这里,我有以下代码开始WebSocket通信。

  // on localhost:3000
  componentDidMount = () => {
    this.ws = new WebSocket('ws://127.0.0.1:5000');

    this.ws.on('open', () => {
      this.ws.send(this.props.userName + ' has joined the Chat.');
    });

    this.ws.on('message', (message) => {
      const messages = this.state.messages;
      this.state.messages.push(message)
      this.setState({ messages: messages })
    });

    console.log('Component mounted.')
  }

每当我在运行时尝试使用npm start与对应的WebSocket服务器进行通信时,该服务器如下所示,并使用node server.js在同一台计算机上启动

// File: server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5000 });

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
    });

    ws.send('something');
});

我遇到以下问题:

Access to fetch at 'http://127.0.0.1:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

为解决这个问题,我已经尝试过:

  1. Chrome的Access-Control-Allow-Origin扩展名无效。
  2. 要在package.json "proxy": "http://localhost:5000"中设置以下代理-也无效。
  3. 作为一种不得已的方法,我尝试使用google chrome --disable-web-security --user-data-dir=/tmp启动google-chrome-在这种情况下,我得到以下信息:GET http://127.0.0.1:5000/ net::ERR_ABORTED 426 (Upgrade Required),从这里我迷路了。

有人可以帮我解决这个问题吗?总的来说这可能吗,或者我的想法有缺陷吗?

我不是任何类型的Web开发人员,通常都使用C ++。抱歉,如果这一切看起来都很愚蠢。

问候 杰克

2 个答案:

答案 0 :(得分:0)

我在Amazon AWS上使用PHP遇到了类似的情况。但这一切消失了,我认为我什么也没做,我相信发生这种情况的原因是AWS自己开始包含Access-Control-Allow-Origin:*标头。

无论如何:

一个简单的解决方法是尝试更改此内容

ws://127.0.0.1:5000

对此

ws://locahost:5000

否则,将服务器端的Access-Control-Allow-Origin:*添加到响应头中

答案 1 :(得分:0)

确保您在客户端上使用的是本地WebSocket对象,而不是“浏览器化”的对象。

因此,像import WebSocket from "ws"这样的导入不能存在于您的React应用程序中。 WebSocket构造函数语句将保持不变。

这是因为ws需要一个普通的TCP套接字,并且无法通过JavaScript在浏览器中获得一个(这就是WebSocket API存在的原因)。

以下问题可能会为您提供更多详细信息: https://github.com/websockets/ws/issues/1367