从Express 4中间件触发socket.io实时通知

时间:2017-01-26 21:12:30

标签: javascript node.js express socket.io

我正在使用socket.io构建实时通知系统。这是我目前的服务器端代码:

bin/www:

var app = require('../app');
var server = http.createServer(app);

var io = app.io
io.attach(server);

server.listen(port, function(err) {
  if (err) console.log(err);
  console.log('Listening on port ' + port + '...');
});

app.js:

var socket_io = require('socket.io');
var express = require('express');

var app = express();
var io = socket_io();
app.io = io;
require('./config/socket')(app.io);

config/socket.js:

var User = require('../controllers/user');

module.exports = function (io) {
    io.on('connection', function (socket) {
        console.log('Socket.io connected');
        socket.emit('connection', "Connection created.");
        socket.on('send notification', function(data) {
            User.createNotification(socket.request.user, data);
        });
    });
};

routes/index.js:

var express = require('express');
var User = require('../controllers/user');
var router = express.Router();

router.post('/order', User.order);
module.exports = router;

controllers/user.js:

var User = require('../models/user').model;
var io = require('socket.io');

module.exports = {
    order: function(req, res) {
        /* some create order code */
        io.emit('send notification', 'Your order was successful!');
        res.sendStatus(200);
   }
}

每当我尝试拨打路由TypeError: io.emit is not a function时,即使我在POST /sendsocket.io文件中明确发起app.js,我也会收到错误bin/www并在controllers/user.js中要求它。我在网上看到的所有例子都从这部分内部发出通知:

io.on('connection', function (socket) {
        socket.emit(event, msg);
    });

但我希望从中间件触发通知,以便在应用程序后端发生某些事件时向用户发送自定义通知。

1 个答案:

答案 0 :(得分:0)

请尝试以下方法:

io.on('connection', function(socket){
    socket.on('xxx', function(obj){
        io.emit('xxx', {xxx: xxx})
    })
})

这会压制您的TypeError: