Created an object in my index.js file, how to make it available in a router file?

Issue

I have an index.js file where I:

  • initialize my Express app instance
  • include a router.js file that defines a POST endpoint
  • create a Socket.IO object

code as follows:

const http = require("http");
const express = require("express");
const router = require("./src/router");


// Create Express webapp
const app = express();

// Create http server and run it
const server = http.createServer(app);
const port = process.env.PORT || 3000;

//Create Socket.IO instance
const io = require('socket.io')(server,{
  cors: {
      origin: "http://localhost:3000",
      methods: ["GET", "POST"],
      credentials:true
  }
});
const cors = require('cors');

At the POST endpoint in router.js, I want to use the Socket.IO object like this:

const Router = require("express").Router;    
const router = new Router();

router.post("/call",(req, res)=>{
  let data = req.body;
  let response = {
    something:`${data.userID} requested a call length ${data.minutes}`
  }
  io.broadcast.emit(response);
  res.send(JSON.stringify(response));
});

module.exports = router;

But this gives me the error:

ReferenceError: io is not defined

How do I make the io object available to this router.post() call? I tried making it a global in index.js via:

global.io = io;

but then the POST call gave me this error:

TypeError: Cannot read property 'emit' of undefined

also tried including io as a parameter in the module.exports function like:

const Router = require('express').Router;
const { tokenGenerator, voiceResponse } = require('./handler');

module.exports = function(io) {
  const router = new Router();
  router.post('/call', (req, res)=>{
    const data = req.body;
    const response = {
      something: `${data.userID} requested a call length ${data.minutes}`,
    }
    io.broadcast.emit(response);
    res.send(JSON.stringify(response));
  });
  return router;
}

and then requiring the router in index.js like:

const router = require('./src/router')(io);

but that gave the same Cannot read property 'emit' of undefined error.

Solution

Read the error message carefully.

but that gave the same Cannot read property ’emit’ of undefined error.

You are successfully passing io.

The problem is that io.broadcast is undefined so it can’t have an emit property.

You can find broadcast on a socket object, not on the server object itself.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published