Socket.io + Node.js Cross-Origin Request Blocked

Waleed Ahmad picture Waleed Ahmad · Jun 5, 2014 · Viewed 126.7k times · Source

I'm using node and socket.io to write a chat application. It works fine on Chrome but mozilla gives an error to enable the Cross-Origin Requests.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://waleedahmad.kd.io:3000/socket.io/?EIO=2&transport=polling&t=1401964309289-2&sid=1OyDavRDf4WErI-VAAAI. This can be fixed by moving the resource to the same domain or enabling CORS.

Here's my code to start node server.

var express = require('express'),
    app = express(), 
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    path = require('path');
server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

On the client side.

var socket = io.connect('//waleedahmad.kd.io:3000/');

Script tag on HTML page.

<script type="text/javascript" src="//waleedahmad.kd.io:3000/socket.io/socket.io.js"></script>

I'm also using .htaccess file in the app root directory. (waleedahmad.kd.io/node).

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Answer

Jason Sebring picture Jason Sebring · Aug 3, 2016

Simple Server-Side Fix

Note: DO NOT USE "socketio" package... use "socket.io" instead. "socketio" is out of date. Some users seem to be using the wrong package.

socket.io v3

docs: https://socket.io/docs/v3/handling-cors/

cors options: https://www.npmjs.com/package/cors

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

socket.io < v3

const io = require('socket.io')(server, { origins: '*:*'});

or

io.set('origins', '*:*');

or

io.origins('*:*') // for latest version

* alone doesn't work which took me down rabbit holes.