“CORS header ‘Access-Control-Allow-Origin’ missing” despite setting cors origin in my server.js

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.

New contributor

user25669529 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật