我正在使用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
和socket.io
文件中明确发起app.js
,我也会收到错误bin/www
并在controllers/user.js
中要求它。我在网上看到的所有例子都从这部分内部发出通知:
io.on('connection', function (socket) {
socket.emit(event, msg);
});
但我希望从中间件触发通知,以便在应用程序后端发生某些事件时向用户发送自定义通知。
答案 0 :(得分:0)
请尝试以下方法:
io.on('connection', function(socket){
socket.on('xxx', function(obj){
io.emit('xxx', {xxx: xxx})
})
})
这会压制您的TypeError:
。