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

CORS #2850

Closed
Kenzku opened this issue Feb 3, 2017 · 11 comments
Closed

CORS #2850

Kenzku opened this issue Feb 3, 2017 · 11 comments

Comments

@Kenzku
Copy link

Kenzku commented Feb 3, 2017

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

@thEpisode
Copy link

Same error

@darrachequesne
Copy link
Member

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

It should be fixed in 2.x (which includes socketio/engine.io#452).

@thEpisode
Copy link

thEpisode commented May 17, 2017

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']
});

`

@thEpisode
Copy link

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

@darrachequesne
Copy link
Member

Great! I guess we can close the issue now.

@princefishthrower
Copy link

@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!

@gowthamyaal
Copy link

@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..?

@thEpisode
Copy link

@gowthamyaal could you show us your code?

@gowthamyaal
Copy link

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.

@gowthamyaal
Copy link

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
[](plugins: [
new DefinePlugin({
'SOCKET_HOST': JSON.stringify(http://192.168.1.5:5000),
}),
new HotModuleReplacementPlugin()
],)

client socket code
[](
//var socket =io.connect('http://192.168.1.5:5000', {
// reconnection: true,
//reconnectionDelay: 1000,
//reconnectionDelayMax : 5000,
//reconnectionAttempts: Infinity
//} );
socket
.on('init', data => {
this.setState({ clientId: data.id })})
.on('request', data => this.setState({ callModal: 'active', callFrom: data.from }))
.on('call', (data) => {
if (data.sdp) {
this.pc.setRemoteDescription(data.sdp);
if (data.sdp.type === 'offer') this.pc.createAnswer();
} else this.pc.addIceCandidate(data.candidate);
})
.on('end', this.endCall.bind(this, false))
.emit('init');
}
} );)

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

@JakeTompkins
Copy link

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}))`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants