Can´t resolve React & SOCKET.IO CORS Error
Asked Answered
G

4

9

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

Gokey answered 1/6, 2018 at 8:38 Comment(0)
G
24

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']});

Gokey answered 4/6, 2018 at 13:14 Comment(1)
openSocket('localhost:8000', {transports: ['websocket']})Overboard
N
8

Use This :

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

    const io = socket(server, {
        cors: {
            origin: "http://localhost:3000",
        }
    });
});
Novgorod answered 4/6, 2021 at 20:8 Comment(2)
Could you add more explanation to your answer? What does your code do and how will it help the OP?Lengel
This code helps only in development. It would not work in production because origin won't be localhost in production.Tightlipped
M
2

I had a problem connecting to a WebSocket which always gives me CORS Error in network tab. @Sebs030 answer worked, fixed that issue by adding transports object to socket instance as follows.

   const socket = io(SOCKET_URL, {
      transports: ['websocket'],
    });

ref: https://github.com/socketio/socket.io-client/issues/641

Mantel answered 26/10, 2023 at 10:7 Comment(0)
P
0

My fix was simply to

  1. update my NPM packages: socket-io (on the client, and the Node server).
npm update

I was using outdated and incompatible packages.

  1. DO NOT FORGET to specify the allowed origins on the server
const server = app.listen('8002', () => {
console.log("Server Up")});

const io = socket(server, {
    cors: {
        origin: "http://localhost:3000", //your own :port or a "*" for all origins
    }
});

});

Patinous answered 14/9, 2022 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.