Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket IO error "Access to XMLHttpRequest has been blocked by CORS policy"

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 "

like image 792
Egan N Avatar asked Jan 15 '20 10:01

Egan N


2 Answers


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);
like image 148
Rahul Verma Avatar answered Nov 16 '22 20:11

Rahul Verma


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: '*',
    }
});
like image 9
shank_fab_worker Avatar answered Nov 16 '22 18:11

shank_fab_worker