javascript - Websocket 服务器和 npm 在 localhost 上启动
问题描述
出于无聊,我目前尝试在本地主机上创建一个简单的聊天应用程序。
为了开始这一切,我从一个基于 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.
为了解决这个问题,我已经尝试过:
- chrome 的 Access-Control-Allow-Origin 扩展没有效果。
- 在 package.json 中设置以下代理
"proxy": "http://localhost:5000"
- 也没有效果。 - 作为一种最后的手段,我尝试使用 google-chrome 启动
google chrome --disable-web-security --user-data-dir=/tmp
- 在这种情况下,我得到以下信息:GET http://127.0.0.1:5000/ net::ERR_ABORTED 426 (Upgrade Required)
从这里开始我迷路了。
谁能帮我解决这个问题?这通常是可能的还是我的想法有缺陷?
我不是任何类型的网络开发人员,通常使用 C++ ......对不起,如果这一切看起来很愚蠢。
问候杰克
解决方案
我在 Amazon AWS 上使用 PHP 遇到了类似的情况。但它消失了,我认为我没有做任何事情,我认为发生这种情况的原因是 AWS 自己开始包括 Access-Control-Allow-Origin:* 标头。
任何状况之下:
一个简单的解决方法是尝试改变这个
ws://127.0.0.1:5000
对此
ws://locahost:5000
否则,将服务器端的 Access-Control-Allow-Origin:* 添加到响应标头
推荐阅读
- sql - 使用 SQL 查询的结果填充 Excel 用户表单文本框
- javascript - 使用异步函数返回 Promise
- python - 如何管理 I/O 设备的多个唯一实例
- android - Intent extras 在我的应用程序中返回 null
- javascript - 计算应计时间
- android - 在 Android 上使用 Hazelcast 会产生随机错误
- scala - 如何将数组的第一个元素与其中的所有其他元素耦合以获得元组列表?
- reactjs - 在平面列表中显示多行
- ios - 在 iOS 上延迟重复的用户通知
- python-3.x - 使用序列模型处理非图像数据的卷积神经网络