How to access the "socket" callback param in a route?


So my problem is that I don’t know how to use the socket parameter in a route.

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);
})

httpServer.listen(port, () => {
  console.log(`Listening on port ${port}`);
})

app.use("/room", roomRouter) 

app.use((req, res) => {
  res.status(404).send("URL not found!");
});

In the router I want to create a room with an id generated by nanoid, but I don’t know how I can use the socket param.

const express = require("express")
const router = express.Router()
const { nanoid } = require("nanoid")

router.post("/create", (req, res) => {
    try {
        const id = nanoid(8)
        socket.join(id)
        res.status(201).json({id: id})
    } catch (err) {
        res.status(500).json({error: err})
    }
})

module.exports = router 

Source: JavaSript – Stack Overflow

October 24, 2021
Category : News
Tags: javascript | node.js | socket.io | sockets | websocket

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.