Home > Mobile >  Socket.io with Node.js returns undefined in route file when trying to emit
Socket.io with Node.js returns undefined in route file when trying to emit

Time:11-24

Iv'e tried to use socket.io to emit data from a route file and it's crushing when i'm calling the route.

Error while getting quotes Cannot read properties of undefined (reading 'emit') TypeError: Cannot read properties of undefined (reading 'emit')

Does anyone know why is this happens?

Thanks.

app.ts


const express = require('express');
const io = require("socket.io");


const indexRouter = require('./routes');
const quotesRouter = require('./routes/quotes');

const app = express();
const listener = app.listen(3001, () => console.log("Listening..."));
const socketsManager = io(listener, {cors: {origin: "*"}});

socketsManager.sockets.on("connection", (socket: any) => {

    console.log("One client has been connected. Total clients: "   socketsManager.engine.clientsCount);

    // Listen to disconnect event from the connected client:
    socket.on("disconnect", () => {
        console.log("A specific client has been disconnected. Total clients: "   (socketsManager.engine.clientsCount - 1));
    });

    socket.on("getQuotes", (quotes: Quote[]) => {
        socket.emit('getQuotes', quotes);
    });
});
app.set('socketio', io);
app.use(express.json());
app.use(express.urlencoded({extended: false}));


app.use('/', indexRouter);
app.use('/quotes', quotesRouter);


module.exports = app;

quotes.ts (route file)

import {NextFunction, Request, Response} from 'express';
const app = require('../app');

const express = require('express');
const router = express.Router();
const quotes = require('../services/quotes');


router.get('/', async function (req: Request, res: Response, next: NextFunction) {
    try {
        let io = req.app.get('socketio');
        io.sockets.emit('getQuotes',await quotes.getMultiple(req.query.page));
        // res.status(200).json(await quotes.getMultiple(req.query.page));
    } catch (err: any) {
        console.error(`Error while getting quotes `, err.message);
        next(err);
    }
});

module.exports = router;

CodePudding user response:

Looks like you've assigned wrong value to socketio. Instead of assigning io, you need socketsManager which is the initialized socket instance

const socketsManager = io(listener, {cors: {origin: "*"}});

So, update your socketio variable definition like this,

app.set('socketio', socketsManager);
  • Related