Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No 'Access-Control-Allow-Origin' header is present on the requested resource. #641

Closed
Neumann-Valle opened this issue Mar 5, 2014 · 108 comments

Comments

@Neumann-Valle
Copy link

XMLHttpRequest cannot load http://domain.com:8080/socket.io/?EIO=2&transport=polling&sid=z1N_9JpKElJJ6b2qAAAL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.com' is therefore not allowed access.
server:

var server = require('http').Server();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('test', function(data){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(8080);

client:
<script>src="http://domain.com:8080/socket.io/socket.io.js"</script>
var socket = io.connect('http://domain.com:8080');
socket.on('connect', function(){
socket.emit( 'test' , { test : 'right' });// if use right on connect , errors out
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});

Can anyone replicate this issue? browser giving error is Chrome, in Firefox just loops..
I think is because when connect and you try to send an emit right away , the client is upgrading connection and fired the emit every time..

It just an assumption , one with better acknowledge could give some more info..

Same test was done with previous repository ver 1.. and it doesn't have same behavior.

@Neumann-Valle
Copy link
Author

Sorry can't post client side code properly, github just blank it out..
Ok , client side test code can be seen..
Anyone could reproduce?

@Neumann-Valle
Copy link
Author

So this isn't important, I passed two days debugging my code to see what I was doing wrong..
This behavior doesn't happens in socket.io ver 0.9.16 and older..

@BartlomiejSkwira
Copy link

I'm experiencing the same issue:

//server
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

function handler (req, res) {
  console.log('handler');
  fs.readFile(__dirname + '../index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}
io.set( 'origins', '*localhost:8080' );

io.sockets.on('connection', function (socket) {
  socket.on('join room', function (data) {
    console.log(data);
    console.log('join');
    socket.emit('user joined', {});
  });
});


//client
socket = io.connect('http://localhost:8080/'); 
_room = room;

console.log('connecting user to socket server');

socket.on('error', function() {
  console.log('there was an error');
});

socket.on('user joined', function(data) { 
  if (data.user_count == 2) {   
    console.log('users are connected');
    users_connected_handler();
  }
});

socket.on('webrtc', function(data){ 
  message_received_handler(data.data);  
});

socket.on('connect', function() {
  console.log('socket connection established');
  console.log("connecting to " + _room)
  socket.emit('join room', {room: _room});
  connected = true;     
});

@BartlomiejSkwira
Copy link

I tried to set the header, but it didin't help

function handler (req, res) {
  console.log('handler');
  fs.readFile(__dirname + '../index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080/');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
      res.send(200);
    }
    else {
      next();
    }
    res.end(data);
  });
}

@Neumann-Valle
Copy link
Author

I see in your server code , io.set() , are you using current socket,io stable 0.9.16?
I only have the issue in socket.io ver1 , haven't test socket.io ~1.0.0-pre but will test to see if still happens..

I found out if you emit right after connect in client you get this error...

@Neumann-Valle
Copy link
Author

And your client code is emitting right after connect.. there is the issue.

@BartlomiejSkwira
Copy link

I'm on node 0.10.24 and latest socket.io.js from https://github.com/LearnBoost/socket.io-client

Nope, I commented out all emits, same issue:
XMLHttpRequest cannot load http://localhost:8080/socket.io/?EIO=2&transport=polling. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

@twhitbeck
Copy link

Issue for me, as well. I want to emit immediately after connection, which is before the transport is upgraded from XHR Polling.

Instructing the client to use the "websocket" transport first might help mitigate the issue, but it still won't help users in browsers that don't support websockets.

var socket = io('http://localhost', {transports: ['websocket', 'polling', 'flashsocket']});

engine.io-client XHR transport really needs CORS support.

@danpe
Copy link

danpe commented Apr 15, 2014

I'm also having this isue.
socket.io-client 0.9.16, server is hosted on heroku.

@Solidary
Copy link

I'm also having this issue.
socket.io-client 0.9.x
I'am using Chronium and Firefox on Ubuntu 12.04

@Linrstudio
Copy link

good ^^*

@adityapatadia
Copy link

https://github.com/theoctal/livenote/blob/master/app.js#L11 look here. The issue is essentially solved by setting middleware for express. This makes good example for those who want to know about how to set middleware.

@oddui
Copy link

oddui commented May 5, 2014

I guess the socket.io connection request doesn't go through the middlewares set on express.

In my case Access-Control-Allow-Origin is set by default as where the request is from. It just works.

I'm using 1.0.0-pre2

@gahula
Copy link

gahula commented May 29, 2014

Experiencing the same problem

@adityapatadia
Copy link

Look at my code, works perfectly.

@gahula
Copy link

gahula commented May 31, 2014

I solved my issue by removing the the transports options....

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server, {origins:'domain.com:* http://domain.com:* http://www.domain.com:*'});
var compress = require('compression');
var redis = require('socket.io-redis');
var uuid = require('node-uuid');
var geoip = require('geoip-lite');
var _ = require('underscore')._;

io.adapter(redis({ host: 'localhost', port: }));

server.listen(, '', function(){
console.log("Server up and running...");
});

........

@avinashega
Copy link

The problem I faced was, serving the client socket.io.js from a different location.

You can avoid this issue by serving the client js file from the same server where you are trying to connect to.

for example, my initial client code was this and it was throwing error

<script src="/socket.io/socket.io.js"></script>
var socket = io.connect('http://mydomain.com/');

once I modified it to this, it worked alright.

<script src="http://mydomain.com/socket.io/socket.io.js"></script>
var socket = io.connect('http://mydomain.com/');

And my server code is,

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 server = http.createServer(app);
io = socketio.listen(server, {log:false, origins:'*:*'});
... //io.connect and events below

@ilovett
Copy link

ilovett commented Jun 4, 2014

👍 I run into this issue when include client socket.io.js from a different domain than the server... using socket.io@1.0.4

@austinh
Copy link

austinh commented Jun 5, 2014

I'm also running into this issue on 1.0.4 when serving it from the socket.io CDN

@ScrewChineseCommunist
Copy link

Me too. Tried:

  1. io.set('origins', ':'); io.set('transports',['websocket','flashsocket','htmlfile','xhr-polling','jsonp-polling']);
  2. express .use(function(req, res, next){})
    All failed. Be screwed for two days, the only progress is guessing socket.io@1.0.4 has new bugs

@gahula
Copy link

gahula commented Jun 5, 2014

Guys,

I had the same problem. I got the same error Chrome and Firefox displayed in console. I have my socket.io and client loading from a sub-domain i.e. chat.mydomain.com. If you are using Node.js, I solved my issue using the following setup.

SERVER SIDE (chat.mydomain.com)

Express version 4
Socket.io version 1.0

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server, {origins:'mydomain.com:* http://mydomain.com:* http://www.mydomain.com:*'});

server.listen([PORT NUMBER], [IP], function(){
console.log("Server up and running...");
});

CLIENT SIDE (mydomain.com)

script src="http://[IP]:[PORT NUMBER]/socket.io/socket.io.js" type="text/javascript"></script>

var socket = io.connect("[IP]:[PORT NUMBER]")

Note 1: Note the [IP] & [PORT NUMBER] are the same in this case.
Note 2: On some host, the port may need to be opened in the firewall. Ask your service provider about the use of websockets.

@oddui
Copy link

oddui commented Jun 5, 2014

Hi guys. The 1.x version works good for me. How are you connecting the server at the client side? Make sure the correct server address and port are used.

The browser might complain CORS issues if the wrong address is requested as no access-control-allow-origin header is set in the response.

@ilovett
Copy link

ilovett commented Jun 6, 2014

IE you visit http://site-a.com/ and load <script src="http://site-a.com/vendor/socket.io.js" /></script>

But your socket server is running on site-b.com -- when you try to connect using io("ws://site-b.com")

@Puigcerber
Copy link

I'm having the same issue with socket.io-client@1.0.4.

I've tried different versions and it works good up to 0.9.17 but problems start with 1.0.0

I don't have any problem if I use the client file from the server.

@Pitel
Copy link

Pitel commented Jun 9, 2014

We are also having this problem.

@cervajs
Copy link

cervajs commented Jun 9, 2014

+1 socket.io-client@1.0.4.

@Puigcerber
Copy link

I have to retract myself. Upgrading to socket.io@1.0.4 in the server side solves the CORS problem with the client library.

@ningacoding
Copy link

ningacoding commented Jul 31, 2017

i fixed the message of headers in NodeJS/Express with this:

response.header('Access-Control-Allow-Credentials', 'true');
response.header('Access-Control-Allow-Origin', request.get('origin')); // because '*' does not exist 
// so equivalent is check origin and allow it, as * is suposed to be "everyone" or "all"

but still getting a:

zone.js:2622 GET http://localhost:PORT/socket.io/?EIO=3&transport=polling&t=LsQEsjS 404 (Not Found)

@ningacoding
Copy link

fixed the 404 (Not Found) with this:

https://stackoverflow.com/a/27394696/2038286

because my config is for Express v4

Solved.

@BigBigWen
Copy link

the same issue here
Because socket.io is by default, a long-polling connection is established first, then upgraded to "better" transports (like WebSocket). If you like to live dangerously, this part can be skipped:

const socket = io(url,{transports: ['websocket']});

@jionet
Copy link

jionet commented Jun 20, 2018

what code is instead of @crossorigin in python?
how can we integrate it in djnago?

@JackyChan
Copy link

the same issue here
socket.io server 2.2.0 and socket.io client 2.2.0

@samuelterra22
Copy link

I have the same problem. socket.io server 2.2.0 and socket.io client 2.2.0
image

@Juanklg
Copy link

Juanklg commented Nov 29, 2018

I have the same problem. V 2.1.1 server and client

@tradingstratagem
Copy link

Same problem here with version 2.2.0.
2.1.1 works fine.

@orange1337
Copy link

Same problem here with version 2.2.0.
2.1.1 works fine.

Have the same problem.
Than's for your reply !!

@ochelset
Copy link

I have the same problem. socket.io server 2.2.0 and socket.io client 2.2.0
image

congnghia0609's solutions worked for me (setting the connection options on the client side), after upgrading to 2.2.0 on the backend

@tradingstratagem
Copy link

I have the same problem. socket.io server 2.2.0 and socket.io client 2.2.0
image

congnghia0609's solutions worked for me (setting the connection options on the client side), after upgrading to 2.2.0 on the backend

Seems to work, thank you!

@samuelterra22
Copy link

I also updated to the latest version and added the tag transports. I did as shown here

@craigcosmo
Copy link

craigcosmo commented Nov 6, 2020

I using code client following, run good:

//Client:

var connectionOptions =  {
            "force new connection" : true,
            "reconnectionAttempts": "Infinity", //avoid having user reconnect manually in order to prevent dead clients after a server restart
            "timeout" : 10000,                  //before connect_error and connect_timeout are emitted.
            "transports" : ["websocket"]
        };
        
        var socket = io('yourdomain.com', connectionOptions);

Wish code fun :)

this solution works in 2020, socket io ver 3.0.0, express 4.16.1, react 16.8.6. Thank you so much

@darrachequesne
Copy link
Member

For future readers:

Using transports: ["websocket"] simply disables HTTP long-polling, which may or may not be what you really want (but it works, since there's no CORS for WebSockets)

Response for Socket.IO v2: the library should automatically add the necessary headers

You can use the origins option to provide a list of authorized domains (all are authorized by default):

const io = require("socket.io")(httpServer, {
  origins: ["https://example.com"]
});

For custom headers/sending cookies (withCredentials), you can use the handlePreflightRequest method:

const io = require("socket.io")(httpServer, {
  origins: ["https://example.com"],

  // optional, useful for custom headers
  handlePreflightRequest: (req, res) => {
    res.writeHead(200, {
      "Access-Control-Allow-Origin": "https://example.com",
      "Access-Control-Allow-Methods": "GET,POST",
      "Access-Control-Allow-Headers": "my-custom-header",
      "Access-Control-Allow-Credentials": true
    });
    res.end();
  }
});

For Socket.IO v3: you must now explicitly enable CORS:

const io = require("socket.io")(httpServer, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
});

If you still get a No 'Access-Control-Allow-Origin' header is present on the requested resource. error message, it might mean that you are not reaching the Socket.IO server. This can be tested with:

curl -X GET https://example.com/socket.io/?EIO=3&transport=polling which should return a JSON (the Engine.IO handshake)

@lhermann
Copy link

lhermann commented Nov 8, 2020

Thank you so much @darrachequesne for summing it up. Works perfectly!

@prettyirrelevant
Copy link

thanks @darrachequesne. I feel this would be a nice addition to the docs, maybe like a note.

@darrachequesne
Copy link
Member

@prettyirrelevant you are absolutely right 👍

Doc for v2: https://socket.io/docs/v2/handling-cors/
Doc for v3: https://socket.io/docs/v3/handling-cors/

@bashiru98
Copy link

i also had the same issue so i just added this in package.json => {"proxy":"backend url"} and in where am using socketio i called
the enpoint as endpoint='/' and it worked fine

@DeividasV
Copy link

For Socket.IO v3: you must now explicitly enable CORS:

this is exactly what was the problem i my case. spent few hours trying to figure out. thanks

@stempest0925
Copy link

The version I used was 3.0.4, and this error also occurred. Many methods were used. The modification according to the official cors had no effect. Finally, the transports were added to the client to run successfully.

io("http://localhost:3000", { transports: ["websocket"] });

@hellosurbhi
Copy link

io("http://localhost:3000", { transports: ["websocket"] });

This worked for me! I'm using version 3.0.4 of socket as well
Thanks @stempest0925

@darrachequesne
Copy link
Member

The modification according to the official cors had no effect.

Could you please explain? Please see the example here: https://github.com/socketio/socket.io-fiddle/tree/cors

Note: disabling HTTP polling (with transports: ["websocket"]) is indeed a solution, though that means that there is no fallback if the websocket connection cannot be established.

@imvickykumar999
Copy link

Issue for me, as well. I want to emit immediately after connection, which is before the transport is upgraded from XHR Polling.

Instructing the client to use the "websocket" transport first might help mitigate the issue, but it still won't help users in browsers that don't support websockets.

var socket = io('http://localhost', {transports: ['websocket', 'polling', 'flashsocket']});

engine.io-client XHR transport really needs CORS support.

.....would 'http://localhost' be valid for the deployed site on Heroku ??

@jgalvan031986
Copy link

Volvi a la version 2.3.0 y funciono a la primera.

@darrachequesne
Copy link
Member

I'm locking the thread, as I feel there's nothing more we can do to help. Please check the documentation here:

@socketio socketio locked as resolved and limited conversation to collaborators Jan 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests