简体   繁体   中英

express.io with express router returns error

When I try to emit the 'ready' event from client on express.io, it shows an error that

{ route: [Function], broadcast: [Function] } 'req.io.route' TypeError: Object # has no method 'ready

I am using express version express@4.12.4.

app.js is as shown below

    var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express.io')();
app.http().io();
//var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

and the index.js file is as below

app = require('express.io')()
app.http().io()
var router = app.Router();

/* GET home page. */
router.all('/', function(req, res, next) {
  res.render('index', { title: 'Express' });


    req.io.route('ready', function(res) {
         console.log('tested..........');
    })


});

module.exports = router;

client side code is as below

<script>

  var socket;
 $(document).ready(function(){

 socket=io.connect(window.location.hostname);
    socket.emit('ready'); 

});

  </script>
</html>

please help me regarding this...

The router isn't a method on the return value of the constructor, it's exported with the module.

var express = require('express.io');
var app = express();
app.http().io()
var router = express.Router();

Also app.http().io() only needs to be called once, so remove it from your routes file.

Try

/* GET home page. */
router.all('/', function(req, res, next) {
    app.io.route('ready', function(res) { //not req.io... 
         console.log('tested..........');
    })
    res.render('index', { title: 'Express' });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM