Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to fix cors error in React with Node

Theodore Kelechukwu Onyejiaku

What is a web socket?

A web socket is a protocol that provides bidirectional and full-duplex communication channels.

Traditionally, when we are on a web page, we communicate with the server through one-way communication. However, with web sockets, communication can be done by both us and the server. Hence, it is no longer us talking to the server alone.


One example of a web socket is a website that tells you the number of people online. Another example of a web socket is real-time chat applications.

Fixing cors error in

1. The React code

Below is the Feact code that emits an event that will be fired in the server. It establishes a two-way connection with the server running on http://localhost:5000.

import {io}  from "";

const ENDPOINT = "http://localhost:5000";
const socket = io(ENDPOINT);

 useEffect(() => {
    // ... other codes
    // Emitting an event that will trigger in the backend

    // ... other codes
  }, [])

2. The NodeJs code

The code below is the server-side implementation of the We require the, and pass the Express server application without some options or configuration.

// ... other codes

const io = require('')(server);

io.on('connection', client => {
  client.on('reply', () => { console.log("a reply detected!")}); // listen to the event

server.listen(PORT, ()=>{
  console.log("Application running successfully on port: "+PORT);

When we run the code above, the following error will be thrown in the console:

The reason for this is that there was no configuration for cors in the implementation of the server-side.
Even with the cors enabled on the server-side, there will still be an error unless there are cors configured along with the implementation.

var cors = require('cors');

How to fix the error

The error is simple to fix. Add cors and the origin that can communicate with the server, and that’s all!

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

In the code above, I added a wildcard as my origin because I would like any origin to access it.




Theodore Kelechukwu Onyejiaku

View all Courses

Keep Exploring