I am working on a project where I have set up a socket.io server.
server.js
const express = require('express');
const app = express();
const http = require('http');
const { Server } = require("socket.io");
const cors = require('cors');
const chatSocket = require('./socketListeners/chatListeners');
const room = require('./socketListeners/roomListeners');
const createRouter = require('./routes/create');
app.use('/creategame', createRouter);
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: 'http://localhost:5173',
methods: ['POST', 'PUT']
}
});
io.on('connection', (socket) => {
console.log('a user connected');
chatSocket(socket);
room(socket);
});
server.listen(3000, () => {
console.log('server listening on port 3000');
});
The initial socket connection and socketListener files are functioning properly and they stop working when I remove the CORS origin from my io declaration.
chatListeners.js
type heremodule.exports = socket => {
socket.on('sendMessage', data => {
socket.to(data.roomId).emit("receiveMessage", data);
})
}
roomListeners.js
module.exports = socket => {
socket.on("joinRoom", data => {
socket.join(data)
})
}
When I want my server to deal with my database I use express routes and fetch requests from the client side.
create.js
const express = require('express');
const router = express.Router();
const Room = require('../models/room');
router.post('/:id', async (req, res) => {
const room = new Room({
roomId: req.params.id,
});
try {
await room.save();
console.log(room);
} catch (error) {
console.error(error);
}
});
router.put('/:id/dicenum', async (req, res) => {
try {
const room = await Room.find({roomId: req.params.id});
room.diceNum = req.body.diceNum;
await room.save();
console.log(room);
} catch(error) {
console.error(error);
}
});
module.exports = router;
Which are called as follows from a react component.
useEffect(() => {
fetch(`http://localhost:3000/creategame/${id}`, {
method: 'POST'
});
}, []);
useEffect(() => {
fetch(`http://localhost:3000/creategame/${id}/dicenum`, {
method: 'PUT',
body: {
diceNum: numOfDice
}
});
}, [numOfDice]);
The problem is the preflight check, it doesn’t know about my allowed origin and the header is not present. If I modify the POST in such a way that causes it to send a preflight, that check fails too.
(Maybe using express routes for this isn’t good practice I really don’t know, if using sockets is fine and would fix my problem let me know, otherwise there has to be some way to get both to function)
my preflight response headers come back like this:
HTTP/1.1 200 OK
X-Powered-By: Express
Allow: PUT
Content-Type: text/html; charset=utf-8
Content-Length: 3
ETag: W/”3-CRsM5C6wvZYWnqALFt2Tj21jrJU”
Date: Fri, 21 Jun 2024 20:22:05 GMT
Connection: keep-alive
Keep-Alive: timeout=5
I’ve been scouring the internet for a few days and I’ve tried moving the CORS object around in my server, opening chrome with –disable-web-security, and turning off ad block extensions as some stack overflow answers have suggested, nothing has changed the outcome apart from making the server reject the socket connection altogether.
I know CORS questions have been asked a million times on here but none that I’ve seen have helped me or seemed to apply to my circumstances, maybe my architecture is just flawed but I thought I’d ask for a solution anyway.
user25669529 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.