Socket.io connection fails between client and server side (Reacr/Node.js)

Viewed 389

I'm trying to get a basic socket connection.

The server looks like this :

    const express = require("express");
    const app = express();
    const port = 4000;
    const server = require("http").createServer(app);
    let io = require("socket.io")(server);

    app.get("/", (req, res) => res.send("Server up"));

    io.on("connection", socket => {
      console.log("a user connected");
    });

    app.get("/", (req, res) => res.send("Hello World!"));

    app.listen(port, () => console.log(`Example app listening on port ${port}!`));

The React component looks like this :

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

    const ChatScreen = () => {

      const socket = io('localhost:4000');


      useEffect(() => {
      }, []);

      return (
        <div className="chatScreen">HI</div>
      );
    };

    export default ChatScreen;

As I got from reading, I should be getting a console.log "a user connected" in the server. But I get these 2 errors :

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

And

polling-xhr.js:267 GET http://localhost:4000/socket.io/?EIO=3&transport=polling&t=N2xy65_ 
net::ERR_FAILED

How should I do it?

2 Answers

In your node js app, you can try to add the following after var app = express(); :

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  next();
});

This error means that your Express server doesn't allow any external request. Your React server is an external server, that's the reason of this error.

To fix this error, simply use the cors middleware as:

const express = require("express");
const cors= require("cors");
const app = express();
const port = 4000;
const server = require("http").createServer(app);
let io = require("socket.io")(server);

app.use(cors());

app.get("/", (req, res) => res.send("Server up"));

io.on("connection", socket => {
  console.log("a user connected");
});

app.get("/", (req, res) => res.send("Hello World!"));

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Documentation: https://expressjs.com/en/resources/middleware/cors.html

Related