xyz83242
xyz83242

Reputation: 824

Unable to connect to NodeJS standalone socket.io with ReactJS

I am looking for the best WS solution for IoT project. I am currently testing my options with Web Sockets. I have tried so far two NPM libraries 'ws' and 'websockets'. They worked great both NodeJS and ReactJS implementation was simple. I am now trying websocket.io. Reading the documentation I struggle to create even a simple working example copying the code directly from the documentation. Since the test code is so simple, I am really confused especially after the positive experience with two previous packages. I am pretty sure I am doing something wrong but I am unable to spot my mistake. I am really thankful for anyone helping to spot what am I not doing right.

NodeJS server instance listening on port 8000 (based on example here: https://socket.io/docs/v4/server-initialization/) :

const io = require("socket.io")();

io.on("connection", socket => { 
   console.log('blip')
});

io.listen(8000);

React client trying to connect to the NodeJS server from port 2000:

import React from "react";
import { io } from "socket.io-client";


class Io extends React.Component {

state = {
   wsConnected: false
}

componentDidMount() {
  const socket = io.connect('http://localhost:8000');
  socket.on("connect", () => {
    console.log('connect',socket.id); 
  });
}

render() {
   const { wsConnected } = this.state;
   return (
     <div>{wsConnected ? 'on' : 'off'}</div>
   )
}

}

export default Io

Upvotes: 0

Views: 106

Answers (1)

Vahid Alimohamadi
Vahid Alimohamadi

Reputation: 5868

It seems you have CORS problem when in polling transport mode, So you can use Socket.io standalone server like this when you are using polling:

const io = require("socket.io")(
    {
        cors: {
            origin: '*',
        }
    }
);

io.on("connection", socket => {
    console.log(`${socket.handshake.headers.origin} connected`);
 });

io.listen(8000);

But it's better use websocket transport if you need persistent http connection. When you are using websocket transport mode, there's no CORS policy.

websocket transport doesn't support http headers like cookies or etc but it is better to use it when there's energy consumption concerns in client side. Also you can force socket.io server to only supports determined transport modes. See socket.io documentations.

Upvotes: 1

Related Questions