0
votes

I am trying to develop a simple chat app using Node, React, Express & Socket.io.

Here is my Node server set up:

const express = require("express");
const cors = require('cors');
const http = require('http');
const socketio = require('socket.io');

// ENV VARS
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

const SERVER_PORT = process.env.SERVER_PORT || 5000;
const HOST = process.env.HOST || "http://localhost";

// INIT
const app = express();
const server = http.createServer(app);
const io = socketio(server);

// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());

io.on('connection', (socket) => {
  console.log('new client connected');
});

// ON LISTEN
server.listen(SERVER_PORT, () => {
  console.log(`app listening at ${HOST}:${SERVER_PORT}`);
});

Here is my client side:

import {io} from "socket.io-client";
  
import './App.css';

const PORT = 5000
const HOST = "http://localhost"
const SERVER_URL = HOST + ':' + PORT
console.log(SERVER_URL);

function App() {
  let socket = io(SERVER_URL);
  return (
    <div className="App">
      aaaa
    </div>
  );
}

export default App;

I simply tried to test the on connection event, Yet I am getting the following error:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

polling-xhr.js:203 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt net::ERR_FAILED

i tried adding:

{origins: '*'}

as socket io doc says but the errors are still showing. What am I doing wrong?

1
Is your reactjs app being served by the same express server you have at the top or is it being served from a different server? - Danoram
What do you mean by different servers? All running on my local - nimrod feldman
When you run your react app with npm start you're starting a development server by default at localhost:3000. I think I should pre-emptively tell you when you build the production version of your app in the future using npm run build you'll need to serve those files somehow as you won't be able to use the dev server then. - Danoram

1 Answers

0
votes

I think changing the order of initialization could help, because your server lacks all the middleware applied to app.

// INIT
const app = express();

// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());

// Create server and listen on PORT after adding middleware
const server = app.listen(PORT, () => {
  console.log(`app listening at ${HOST}:${SERVER_PORT}`)
});

// Try to avoid wilcard ('*') origins
const io = socketio(server, { cors: { origin: '*' } });

// Handle socketio connections
io.on('connection', (socket) => {
  console.log('new client connected');
});

// EOF