I trying to setup a very simple App to get familar with using SOCKET.IO in an React APP. Server looks like this:
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);
and React Client, which is setup with Create-React-App, looks like this:
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;
So basically server is sending a timestamp to the client using socket.io and this get´s then reflected there every second. However this setup is running into the following CORS issue:
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.
I checked all the solutions provided here in other questions, i.e. io.origins{*:*}
, I tried the same with using express.js and the cors npm package, etc. but the error remains. Any idea what I am doing wrong here? I am using Chrome Browser. Thanks a lot in advance