express.js 4 and sockets with express router

后端 未结 5 1793
灰色年华
灰色年华 2020-12-05 00:58

I\'m trying to create a really simple node API using express.js 4 but I need a few \'realtime\' events for which I added socket.io. I\'m fairly new to both so I\'m likely m

5条回答
  •  天涯浪人
    2020-12-05 01:36

    One more option is to use req.app.

    app.js

    const express = require('express');
    const path = require('path');
    const logger = require('morgan');
    const api = require('./routes/api');
    
    const app = express();
    const io = require('socket.io').listen(app.listen(3000));
    
    // Keep the io instance
    app.io = io;
    
    app.use(logger('dev'));
    app.use(express.static(path.join(__dirname, 'public')));
    
    // ...
    
    app.use('/api', api);
    
    module.exports = app;
    

    routes/api.js

    const express = require('express');
    const router = express.Router();
    
    router.put('/foo', function(req, res) {
        /*
         * API
         */
    
        // Broadcast the updated foo..
        req.app.io.sockets.emit('update', foo);
    });
    
    module.exports = router;
    

提交回复
热议问题