简体   繁体   中英

CORS node js issue

Having gone through multiple posts on stack I still couldn't find a right answer.

Checked the documentation on CORS extension as well.

I have the following server code up and running:

var WebSocketServer = require("ws").Server
var http = require("http")
var express = require('express')
var cors = require('cors')
var app = express();

app.use(cors());
var port = process.env.PORT || 9000

var server = http.createServer(app)
server.listen(port)
var count   = 0;
var clients = {};
var rooms   = {};
var wss = new WebSocketServer({server: server})
wss.on("connection", function(ws) {
    ws.on("create-room", function(data) {
        rooms[data] = {creator : data.user_id, created : new Date()}
    })
    ws.on("close", function() {
        console.log("websocket connection close")
    })
})

But I get:

XMLHttpRequest cannot load http://localhost:9000/socket.io/?EIO=3&transport=polling&t=LE-CbU0 . A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin ' http://localhost:8100 ' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

If I comment the line with app.use(cors());

I get :

XMLHttpRequest cannot load http://localhost:9000/socket.io/?EIO=3&transport=polling&t=LE-Cwb8 . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8100 ' is therefore not allowed access. The response had HTTP status code 404.

So clearly my server is up and running ok but

As the error message says, the wildcard Access-Control-Allow-Origin origin cannot be used with Access-Control-Allow-Credentials . By default, the cors module uses a wildward origin, and by default socket.io requires credentials (or so it seems here, anyway). What you need to do is read the Origin header of of the request and include it in the Access-Control-Allow-Origin of the response.

Fortunately, cors makes this very easy: in order to reflect the request origin, pass in an options object with an origin: true property. You also need a credentials: true property to allow credentials at all:

app.use(cors({
    origin: true,
    credentials: true
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM