Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
Socket.io in express js : Router.use requires middleware function but got undefined

I am trying to integrator socket.io in my express js application (Created by express generator).

Here is the answer i've followed

But it didn't worked.

Added following in bin/www

app.io = require('socket.io')();
app.io.attach(server);

When i modify app.use('/', index); with app.use('/', require('./routes/index')(app.io)); in app.js file i got the following error

*

Router.use requires middleware function but got undefined

*

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Here is how you can implement socket.io with express.

var express = require('express')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//serve static files and index.html
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });

io.on('connection', function(socket){
    //logic handled in here
});

http.listen(7000,function(){ console.log('listening on port: 7000'); });

The above code has one route for handling the serving of index.html, but of course you can extend with additional routes the same way you would in any other app.

Here is how you can have access to socket.io within a route in express generator.

In www:

var server = http.createServer(app);
var io = require('socket.io')(server);
module.exports = {io:io}

Within index.js

router.get('/', function(req, res, next) {
  var io = require('../bin/www')
  console.log('I now have access to io', io)
  res.render('index', { title: 'Express' });
});

Note, the above example is purely showing you how to gain access to the io object within index.js. There are many better ways to require socket.io and pass the io object around, but those decisions seem to be outside the scope of this question.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda