Socket IO issue: CORS policy is blocking access to XMLHttpRequest

My application recently encountered an error.

"Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

When connecting to socket.io, I haven't found a solution to this issue yet. Details are described in the image below. Has anyone else faced this error before?

https://i.stack.imgur.com/m1n3I.png

Server configuration:

var express = require('express');
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();
});
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server, {log:false, origins:'*:*'});

Client configuration:

var socket = io('https://my-service-domain', {transports: ['polling']});
socket.on(channel_id, function(data){
     // some code
});

I attempted to change the websocket connection option to

var socket = io('https://my-service-domain', {transports: ['websocket']})
, but it resulted in the following error:

"WebSocket connection to 'wss://my-service-domain/socket.io/?EIO=3& transport = websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 "

Answer №1


When working with Socket.IO version 3, make sure to explicitly enable Cross-Origin Resource Sharing (CORS) in your setup.
const io = require("socket.io")(httpServer, {
  cors: {
    origin: "http://localhost:8080",
    methods: ["GET", "POST"]
  }
});

httpServer.listen(3000);

Answer №2

After spending 2 hours on it, I finally found the solution that works perfectly. All you need to do is replace the existing code with this:

const express = require("express")
var app = express();
var server = app.listen(4000);
var io = require('socket.io')(server, {
    cors: {
      origin: '*',
    }
});

Answer №3

Give this a shot:

const server = new HTTPServer(io, {
  permission: {
    allow: true,
    validate: true,
  },
  compatibilityMode: true,
});

I found success using the code above. For more details, check out this reference link

Answer №4

When dealing with multiple URLs:

const io = require('socket.io')(server, {
    cors: {
      origin: ['url1','url2',..]
    }
});

Answer №5

In the case that you are utilizing the HTTPS protocol, consider implementing this code snippet:

const https = require('https');

Answer №6

Encountering a similar error where your request access has been blocked? Try updating your code from..... const socket = io('http://localhost:8000'); to the following: const socket = io('http://localhost:8000',{transports: ['websocket']});

This adjustment should allow your code to function properly.

Answer №7

If you're looking to address cross-origin resource sharing (CORS) in your application, consider using the npm package called cors. Begin by installing CORS with the command below:

npm install cors

Next, import the CORS package at the top of your application file like so,

const cors = require('cors');

Then, utilize this constant variable as a middleware in your code,

app.use(cors());

This setup will effectively manage all CORS-related configurations and requirements for you.

Please Note: Remember to include the app.use(cors()); line before initializing your routers to ensure proper functionality.

Answer №8

One method I discovered to work around this issue is by utilizing the prependListener function. Please note that this solution specifically applies to socket.io version 4.1.0 and later.

const express = require('express')
const app = express()
const server = require('http').createServer(app);
const io = require('socket.io')(server)
io.on('connection', socket=>{
   // handle all socket events here
});

// Use these lines for handling CORS
server.prependListener("request", (req, res) => {
   res.setHeader("Access-Control-Allow-Origin", "*");
});
// You can specify a specific domain/servername instead of using "*"
server.listen(7000, () => {
   console.log("Socket server is now running");
});

Answer №9

After deploying my nodejs app with socket.io on Heroku, I encountered an error in my browser. It turned out that the issue was caused by not including a start script in the package.json file. Without this script, Heroku was unable to initiate my app. Once I added the start script as required, the problem was quickly resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise after upgrading Node and npm, causing an inability to execute any npm command

Following an upgrade to the latest Node and npm version, I encounter an error when attempting any npm command: C:\Users\...>npm doctor TypeError: Cannot read property 'prefix' of undefined at parseField (C:\Users&bs ...

Navigable MEAN.js paths for CRUD operations

Exploring the world of MEAN stack with mean.js as my structure framework. Playing around with Express and Angular routing to understand how it all works. Here's one of my server routes: app.route('/api/projects/:projectId') .get(users. ...

error encountered in node.js express route.get() function

I have used express-generator and installed the necessary dependencies. The only thing I've changed is the app.js file, which I have included here. Upon running npm start, I encountered an error. I have provided both the error message and the app.js ...

Tips for sending a variable from Express to a Jade template

I have searched for answers on this topic, but I haven't found one that addresses the entire process. I am feeling quite stuck. Below is my code: express code res.render('index', {expressVar:"My Example"}); template.jade doctype html ...

Store the user's login credentials securely in the browser's local storage

Currently, I am implementing user authentication in Node Express with EJS using JWT. The generated token is stored in cookies using the following code: res.cookie('authorization', token, {maxAge: 3 * 60 * 60 * 1000}); During verification, I can ...

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

When the Node.js code is executed, it will send back an XML element for any ID parameter

I am having trouble getting the content to load when I type any of the element's ID from the last XML. Currently, the code only returns content if I type in the last element's ID. How can I modify it to load content and page for any of the elemen ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

What could be causing the request.body to be considered as undefined?

My server has a node-js setup with bodyparser and other modules: var express = require('express'); var dbcon = require('./app/db/databaseconnection'); var bodyParser = require('body-parser'); var app = express(); var router ...

Module not found even after executing npm install within Docker container

I am currently in the process of Dockerizing a node application, but I'm encountering an issue when attempting to start the app using: docker-compose -f docker-compose -f docker-compose.override.yml An error message stating ** Error: Cannot find mod ...

After deploying my Node.js/Express.js application to AWS Lambda, I encountered a bcrypt error

I'm currently facing an issue with getting my express.js app to run on AWS Lambda. Despite successfully deploying it using the serverless framework, I encounter a 500 internal error when testing requests. The log displays the following error message: ...

Node.js encountered an error: Module "express" not found

I just created my first node.js application, but I'm having trouble finding the express library: C:\ChatServer\Server>node server.js module.js:340 throw err; ^ Error: Cannot find module 'express' at Function. ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

Is npm global feature going unused?

I encountered some npm issues in the past and followed solutions from sources like Stack Overflow and GitHub to fix them. Although they seemed to work at first, I recently discovered that my global npm packages are not being recognized or utilized. Whenev ...

What is the best way to upload a file in Node.js using Express and Multer?

When attempting to send a file from the front end to my node js server, I encountered an issue with receiving the file on the back end. Here is the code snippet: <form id="file-upload-form" class="uploader" action="/uploa ...

Using fs.createWriteStream across multiple processes

Is there a way to efficiently manage multiple Node.js processes writing to the same file using fs.createWriteStream without overwriting data? By default, when fs.createWriteStream is called, it clears out the file. I aim to clear the file once and only app ...

Unable to utilize npm package

Currently in the process of developing an npm package for publication. I've been following the guidelines outlined in this documentation, and everything was going smoothly until I encountered an issue with the require part. Despite successfully instal ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...