我尝试设置一个非常简单的应用程序来熟悉在 React 应用程序中使用 SOCKET.IO。服务器看起来像这样:
const io = require('socket.io')();
io.origins('*:*');
io.on('connection', (client) => {
client.on('subscribeToTimer', (interval) => {
console.log('client is subscribing to timer with interval ', interval);
setInterval(() => {
client.emit('timer', new Date());
}, interval);
});
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
使用 Create-React-App 设置的 React Client 如下所示:
import React, { Component } from 'react';
import './App.css';
import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:8000');
function subscribeToTimer(cb) {
socket.on('timer', timestamp => cb(timestamp));
socket.emit('subscribeToTimer', 1000);
}
class App extends Component {
constructor(props) {
super(props);
subscribeToTimer((timestamp) => {
this.setState({
timestamp
});
});
}
state = {
timestamp: 'no timestamp yet'
};
render() {
return (
<div className="App">
<div className="App-header">
<h2>Our awesome drawing app</h2>
</div>
This is the value of the timer timestamp: {this.state.timestamp}
</div>
);
}
}
export default App;
所以基本上服务器使用socket.io向客户端发送时间戳,然后每秒都会反射(reflect)出来。 然而,此设置遇到了以下 CORS 问题:
localhost/:1 Failed to load http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MEwUo-e: Redirect from 'http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MEwUo-e' to 'https://localhost:8443/socket.io/?eio=3&transport=polling&t=MEwUo-e' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我检查了其他问题中提供的所有解决方案,即io.origins{*:*}
,我尝试使用express.js和cors npm包等进行相同的操作,但是错误仍然存在。知道我在这里做错了什么吗?我正在使用 Chrome 浏览器。提前非常感谢
最佳答案
好的,我终于在这里找到了解决方案:https://github.com/socketio/socket.io-client/issues/641
这导致我将第 4 行中客户端的代码更改为 const socket = openSocket('http://localhost:8000', , {transports: ['websocket']});
关于node.js - 无法解决 React 和 SOCKET.IO CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639337/