Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can´t resolve React & SOCKET.IO CORS Error

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

like image 886
Sebs030 Avatar asked Jun 01 '18 08:06

Sebs030


2 Answers

OK, I finally found the solution here: https://github.com/socketio/socket.io-client/issues/641 which lead me to change on the code on the client side in line 4 to const socket = openSocket('http://localhost:8000', , {transports: ['websocket']});

like image 186
Sebs030 Avatar answered Sep 22 '22 12:09

Sebs030


Use This :

const server = app.listen('3001', () => {
    console.log("Server Up")});

    const io = socket(server, {
        cors: {
            origin: "http://localhost:3000",
        }
    });
});
like image 29
HOSENUR Avatar answered Sep 18 '22 12:09

HOSENUR