Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda