Socket.io: CORS

Created on 3 Feb 2017  ·  11Comments  ·  Source: socketio/socket.io

hej,

how I can remove the response header Access-Control-Allow-Origin?
looks like the settings {'origins' : 'asfdasd.com'} does not work.

POST /socket.io/?EIO=3&transport=polling&t=1481690658797-5&sid=Dp18NNt_bWPkB4rGAAAP HTTP/1.1
Origin: https://evilhost.net

HTTP/1.1 400 Bad Request
Content-Type: application/json
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://evilhost.net
Date: Fri, 03 Feb 2017 12:27:42 GMT
Connection: keep-alive
Transfer-Encoding: chunked

Most helpful comment

@thEpisode I realize this is an old thread, but that final link was what fixed it for me! Most of the Express tutorials have app.listen(...) but in the case of using socket.io you need to be sure that in your index.js you call http.listen(...) and NOT listen on the app object, or you'll get this CORS issue. Such a small thing!

All 11 comments

Same error

@Kenzku @thEpisode Which version of socket.io are you using?

It should be fixed in 2.x (which includes https://github.com/socketio/engine.io/pull/452).

Hi @darrachequesne thanks for reply. I'm creator of Crawler Site (https://www.crawlersite.com) and we use Socket.io to send data to our servers and all our infraestructure is on Microsoft Azure, all test and first beta testers uses Azure and we haven't problems, but a new betatester use another cloud service provider and he reported a bug. The problem is CORS, we read all questions on Google!! and searching solutions we notice that Socket.io is updated to 2.0 (exactly 2.0.1 in server), we update client and server but problem persist, we use Express that also reported problems with CORS and we resolved it.

We are very frustated because all solutions on Google didn't resolve the problem, sorry for no posting this on GitHub issues or StackOverflow but we want to give all details possible to solve it. Some URLs to test:

Backend URI: http://crawlerbackend.azurewebsites.net
Testing Express CORS: https://testcors.000webhostapp.com (this hosting is used by tester)
Testing Socket.io CORS: https://testcrawlersite.000webhostapp.com (please see console)
Our primary site to test: http://crawler-test.azurewebsites.net (with new modifications also is broken)
Socket.io file: http://crawlerbackend.azurewebsites.net/socket.io.js

Part of our app.js:
`
var path = require('path');
var bodyParser = require('body-parser');
var cors = require('cors');
var express = require('express');
var app = express();

// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(bodyParser.json()); // support json encoded bodies
app.use(cors({ origin: '*' }));
// Settings for CORS
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.header('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', false);

    // Pass to next layer of middleware
    next();
});

var server = app.listen(cross.NormalizePort(process.env.PORT || 3500));
var io = require('socket.io').listen(server, {
    log: false,
    agent: false,
    origins: '*:*',
    transports: ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling', 'polling']
});

`

Problem resolved!! @Kenzku please review this documentation: https://github.com/socketio/socket.io/blob/master/docs/API.md#serveroriginsvalue and see the code: https://github.com/socketio/socket.io/blob/master/lib/index.js#L67 and check if you use Express (this example is very useful): https://github.com/socketio/socket.io#in-conjunction-with-express

Great! I guess we can close the issue now.

@thEpisode I realize this is an old thread, but that final link was what fixed it for me! Most of the Express tutorials have app.listen(...) but in the case of using socket.io you need to be sure that in your index.js you call http.listen(...) and NOT listen on the app object, or you'll get this CORS issue. Such a small thing!

@frewinchristopher i am following the same pattern as you mentioned above, locally its working fine but in remote it throws (Reason: CORS request did not succeed). where i am wrong..?

@gowthamyaal could you show us your code?

Thanks for your concern, but Solved the CORS issue, as I was using AWS there is a conflict with elastic ip and local ip, later i had changed the socket listening ip as 0.0.0.0, this solved my issue.

Now facing the race condition issue in remote, i am using webpack-dev-config, i had tried to use io connect and emit code in the same file but end up with undefined error

webpack-dev-config

client socket code
;)

the commented lines did work for me.... could anyone help me with this....thanks in advance

I have followed all of the solutions I could find and still have yet to send a working response. If someone could take a look I'd be very appreciative.

`const express = require('express')
const http = require('http')
const socketIO = require('socket.io')
const cors = require('cors')

// Host port
const port = 3001

const app = express()
app.use(cors())
// Server instance
const server = http.createServer(app)
// Creat socket using the server instance
const io = socketIO(server)

io.origins("http://localhost:3000")

io.on('connection', socket => {
console.log("User Connected")

socket.on('disconnect', () => {
    console.log("User Disconnected")
})

socket.on('send message', (message) => {
    io.sockets.emit('send message', message)
})

})

server.listen(port, () => console.log(Listening on port ${port}))`

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MyMomSaysIAmSpecial picture MyMomSaysIAmSpecial  ·  4Comments

MichaelJCole picture MichaelJCole  ·  3Comments

dmuth picture dmuth  ·  3Comments

gCurtisCT picture gCurtisCT  ·  4Comments

kootoopas picture kootoopas  ·  4Comments