express.js 4 and sockets with express router

后端 未结 5 1788
灰色年华
灰色年华 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:50

    I've modified your files a little bit, may you check if it works?

    You can pass the io you've defined to your routes like below;

    require('./routes/api')(app,io); 
    

    I didn't test the Socket.IO parts but there is no syntax error and routes also working.

    server.js file:

    var express = require('express');
    var app = express();
    var path = require('path');
    var logger = require('morgan');
    
    var io = require('socket.io').listen(app.listen(3000));
    
    app.use(logger('dev'));
    app.use(express.static(path.join(__dirname, 'public')));
    
    io.sockets.on('connection', function (socket) {
        console.log('client connect');
        socket.on('echo', function (data) {
        io.sockets.emit('message', data);
     });
    });
    
    require('./routes/api')(app,io); 
    
    console.log("Server listening at port 3000");
    

    api.js:

    module.exports = function(app,io) {
    app.put('/foo', function(req, res) {
    
        /* 
    
          do stuff to update the foo resource 
    
          ...
    
         */
    
    
        // now broadcast the updated foo..
    
        console.log("PUT OK!");
    
        io.sockets.emit('update'); // how?
        res.json({result: "update sent over IO"});
    
    });
    }
    

提交回复
热议问题