2017-01-26 64 views
0

我正在使用socket.io構建實時通知系統。這是目前我的服務器端代碼:從Express 4中間件觸發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 /send即使我清楚地發起我app.jsbin/www文件socket.io並要求它在controllers/user.js。我在網上看到這個部分內發出通知所有的例子:

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

但我想從中間件觸發了我的通知,這樣我就可以發送自定義通知用戶當某些事件在應用程序後臺發生。

回答

0

嘗試,而不是執行以下操作:

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

這應該壓抑自己的TypeError: