CORS node js issue

浪尽此生 提交于 2021-02-20 07:30:11

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/36267171/cors-node-js-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!