I'm trying to create a room when a post request to /room/create, but I get this error: TypeError: Cannot read property 'join' of undefined. I have created a middleware that lets me use the io object in a request, but apparently it still doesn't work.
server.js:
const express = require("express");
const app = express();
const { createServer } = require("http");
const { Server } = require("socket.io");
const port = process.env.PORT || 5000;
const httpServer = createServer(app)
const roomRouter = require("./routers/roomRouter")
const io = new Server(httpServer, {
cors:{
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
})
io.on("connection", (socket) => {
console.log(socket.id);
})
app.use((req, res, next) => {
req.io = io
next()
})
httpServer.listen(port, () => {
console.log(`Listening on port ${port}`);
})
app.use("/room", roomRouter)
app.use((req, res) => {
res.status(404).send("URL not found!");
});
roomRouter.js:
const express = require("express")
const router = express.Router()
router.post("/create", async(req, res, next) => {
try {
// This line causes the error:
req.io.socket.join("room1")
const id = 27432
res.status(201).json({id: id})
} catch (err) {
console.log(err);
res.status(500).json({error: err})
}
})
module.exports = router