我尝试设置一个非常简单的应用程序,熟悉在React APP中使用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向客户端发送一个时间戳,然后每秒都会反映出来。 但是,此设置遇到以下CORS问题:
localhost /:1无法加载 http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MEwUo-e: 重定向 'http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MEwUo-e' 至 'https://localhost:8443/socket.io/?eio=3&transport=polling&t=MEwUo-e' 被CORS政策阻止:没有'Access-Control-Allow-Origin' 标头出现在请求的资源上。起源 因此,“http://localhost:3000”不允许访问。
我检查了其他问题中提供的所有解决方案,即io.origins{*:*}
,我尝试使用express.js和cors npm包等,但错误仍然存在。知道我在这里做错了什么吗?我正在使用Chrome浏览器。非常感谢提前
答案 0 :(得分:1)
使用这个:
const server = app.listen('3001', () => {
console.log("Server Up")});
const io = socket(server, {
cors: {
origin: "http://localhost:3000",
}
});
});
答案 1 :(得分:0)
好的,我终于在这里找到了解决方案:https://github.com/socketio/socket.io-client/issues/641
这导致我将第4行中客户端的代码更改为const socket = openSocket('http://localhost:8000', , {transports: ['websocket']});