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

Time:09-06

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.

CodePudding user response:

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.

  • Related