Configuring Express 4.0 routes with socket.io

前端 未结 3 744
渐次进展
渐次进展 2021-01-31 22:33

I have created a new Express application. It generated app.js for me and I have then created the following index.js bringing in socket.io:

var app = require(\'./         


        
3条回答
  •  天命终不由人
    2021-01-31 23:09

    The route:

    const Router = require('express').Router
    
    const router = new Router();
    
    router.get('/my-route', (req, res, next) => {
        console.log(req.app.locals.io) //io object
        const io = req.app.locals.io
        io.emit('my event', { my: 'data' }) //emit to everyone
        res.send("OK")
    });
    
    module.exports = router
    

    The main file:

    const app = require('express')()
    const server = require('http').Server(app);
    const io = require('socket.io')(server)
    const myroute = require("./route") //route file dir
    
    app.use(myroute);
    
    server.listen(3000, () => {
        console.log('¡Usando el puerto 3000!');
    });
    
    app.locals.io = io
    

提交回复
热议问题