9

my app has recently received an error

"Access to XMLHttpRequest at 'https://my-service-domain/socket.io/?EIO=3&transport=polling&t=M-eWtUQ' from origin 'https://my-app-domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

when i connecting to socket.io. I have not yet found a solution to this problem, I will describe in detail as the image below, has anyone ever encountered this error.

enter image description here

Server config:

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 config:

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

I tried to switch the websocket connection option var socket = io('https://my-service-domain', {transports: ['websocket']}), I got the error

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

1

9 Answers 9

18

If you are using Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS).
const io = require("socket.io")(httpServer, {
  cors: {
    origin: "http://localhost:8080",
    methods: ["GET", "POST"]
  }
});

httpServer.listen(3000);
2
  • Indeed in works for browsers, but what about mobile apps? Their origin always changes..
    – Pierre
    Feb 1, 2021 at 13:38
  • Thanks this saved me from few hours of online research :)
    – Syam Kumar
    Apr 30, 2021 at 18:26
9

It is 100% working.. I have spend 2 hours in it and at last find the answer . Just replace code with this...

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

If you are using HTTPS protocol, then try using the following snippet:

var http = require('https');
0
0

If you are facing the same kind of error where your access to the request has been blocked then change your code from..... const socket = io('http://localhost:8000'); to this const socket = io('http://localhost:8000',{transports: ['websocket']});

this will make your code to run

1
  • This does not solve this issue and I don't see why it would
    – eemilk
    Aug 6, 2021 at 10:55
0

For multiple urls:

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

You can try to use cors npm package. Install CORS using the following command:

npm install cors

Then at the top of your application file, import the installed CORS package as,

const cors = require('cors');

then use this constant variable as middleware,

app.use(cors());

and it will handle all the CORS related options and settings you need.

Note: You should use app.use(cors()); line before initiating your routers. Otherwise it may not work.

0

One way i found around this was by using "prependListener". This will only work for socket.io 4.1.0 and above

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

// Magic Lines
server.prependListener("request", (req, res) => {
   res.setHeader("Access-Control-Allow-Origin", "*");
});
// instead of "*" your can also add the other domain/servername
server.listen(7000, () => {
   console.log("This is the socket server running");
});
0

Try this:

const io = new Server(httpServer, {
  cors: {
    origin: true,
    credentials: true,
  },
  allowEIO3: true,
});

This works for me. I saw this answer here

-1

When I hosted on Heroku my nodejs app that uses socekt.io I got the same error in my browser. The problem was that I didnot add a start script in package.json file. So heroku could no way start my app. When I added the start script, then the problem was solved.

2
  • What is start script?
    – Oliver D
    Nov 10, 2020 at 16:36
  • @OliverD I think he is referring to package.json scripts, like test and start. If you don't define a start script in your package.json file, it may cause startup failures in various deploment environments. May 18, 2021 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.