has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

When your website calls the Socket.IO backend API from another domain, the browser console displays the error message

Access to XMLHttpRequest at ‘http://…:3000/socket.io/?EIO=3&transport=polling&t=N7Y-Fot’ from origin ‘http://….com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

To enable Cross-origin resource sharing add the code to the top of your Socket.IO server.js file

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

// require 'cors'
const cors = require('cors')
// Add CORS before any other routing
server.use(cors());

const http = require('http').createServer(server);
const io = require('socket.io')(http);

Before building the application install the cors package

npm install cors

Leave a comment

Leave a Reply