CORS node js issue

After going through several messages on the stack, I still could not find the correct answer.

Check out the CORS documentation.

I have the following server code:

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 . wildcard '*' cannot be used in the "Access-Control-Allow-Origin" header when the credential flag is true. the origin of ' http: // localhost: 8100 ' is therefore not allowed. XMLHttpRequest credential mode is controlled withCredentials.

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

I get:

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

So my server is working fine, but

+5
source share
1 answer

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

Fortunately, cors makes this very simple: to reflect the start of the request, go to the options object with the property origin: true . You also need the credentials: true property to allow credentials in general:

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

Source: https://habr.com/ru/post/1245928/


All Articles