Access-Control-Allow-Origin error with Nodejs and Reactjs application

Asked

Viewed 56 times

0

I’m developing a real-time chat application, using Reactjs on the front end and Node.js on the back end. I have configured the Node server with Socket.io for the application. When entering the chat page itself, it must connect to the server in question. However, when trying to connect the console returns the error:

Access to Xmlhttprequest at http://localhost:5000/socket.io/? EIO=4&transport=polling&t=Nhg2tfs' 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:198

and just below:

GET http://localhost:5000/socket.io/? EIO=4&transport=polling&t=Nhg2tfs
net:ERR_FAILED

Client side runs on port 3000 and server on port 5000 of localhost.

I’m using

  • Cors v2.8.5
  • Express v4.17.1
  • Nodemon v2.0.12
  • Socket.io v4.1.3

Filing cabinet index.js Server Side

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

const PORT = process.env.PORT || 5000;

const router = require('./router');

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

io.on('connection', (socket) => {
    console.log('Novo usuário conectado!');

    socket.on('disconnect', () => {
        console.log('Usuário desconectado!');
    })
});

app.use(cors());
app.use(router);

server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));

Filing cabinet index.js - Client Side

import React, { useState, useEffect } from 'react';
import queryString from 'query-string';
import io from 'socket.io-client';

let socket;

const Chat = ({ location }) => {
    const [name, setName] = useState('');
    const [room, setRoom] = useState('');
    const ENDPOINT = 'localhost:5000';

    useEffect(() => {
        const { name, room } = queryString.parse(location.search);

        socket = io(ENDPOINT);
        
        setName(name);
        setRoom(room);

        console.log(socket);
    });

    return (
        <h1>Chat</h1>
    );
}

export default Chat;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I would like you to help me solve this mistake, please.

2 answers

2

Oops, try adding this to your socket:

export const io = socketio(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
})

If not, I would tell you to make another http server only pro socket on another port like this:

import { createServer } from 'http'
import socketio from 'socket.io'

const socket = createServer()
export const io = socketio(socket, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
})

io.on('connection', (socket) => {
    console.log('Novo usuário conectado!');

    socket.on('disconnect', () => {
        console.log('Usuário desconectado!');
    })
});

socket.listen(4000)
  • Thank you, the first option worked ;)

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.