Reputation: 63
anybody could help me out with this. The code below is not handling cors properly. When i send http request the headers coming back are fine, however trying to get a connection through socket.io-client i get no cors headers in response. Anybody knows why is that happening and how to fix it?
const express = require("express");
const http = require('http')
const app = express();
const socket = require("socket.io");
const cors = require("cors");
app.use(cors());
app.options('*', cors())
app.use(express.json());
app.get('/', (req,res)=>{
res.send({e: 'elo'})
})
const server = http.createServer(app);
const io = socket(server);
io.on("connection", (socket) => {
console.log("user connected to: ")
});
io.on("message", (data) => {
console.log(data);
});
server.listen(3001);
Upvotes: 0
Views: 26
Reputation: 583
Socket IO handles CORS separately than express. See the following:
socket.io v2 docs
const io = socket(server, {
origins: ["https://example.com"]
});
socket.io v3 docs
const io = socket(server, {
cors: {
origin: "https://example.com",
methods: ["GET", "POST"]
}
});
In your case, you would pass *
to the origin
or origins
property (depending on the version you are using) to allow all origins. Although locking it down to certain origins is recommended.
Upvotes: 1