我有一个NodeJS Express服务器和Angular2前端的小项目。服务器具有API接口。其主要部分是: / api / alert 。我想执行以下操作:如果 / api / alert 收到请求,则socket.io会向所有连接的客户端广播一个事件。
server.js
var http = require('http'),
express = require('express'),
app = module.exports.app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
db = require('./config/db'),
path = require('path');
mongoose.Promise = global.Promise;
mongoose.connect(db.url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
var routes = require('./server/routes/index');
routes(app);
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(port);
console.log('Server started on: ' + port);
服务器/路由/ index.js
const deviceRoute = require('./devicesRoute');
const alertRoute = require('./alertsRoute');
module.exports = function(app) {
deviceRoute(app);
alertRoute(app);
}
服务器/路由/ alertRoute.js
'use strict';
module.exports = function(app) {
var alertsService = require('../services/alertsService');
app.route('/api/alert')
.post(alertsService.createAlert);
};
服务器/服务/ alertService.js
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
};
我无法将io和服务器变量传递给函数(来自server.js)。我怎样才能做到这一点?什么是最简单的方法?
谢谢!
答案 0 :(得分:0)
首先,您需要从server.js导出app和server对象,并将套接字传递给中间件中的响应,如下所示:
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
...
module.exports = {app: app, server: server};
然后,您可以要求在server.js中创建的服务器实例(取决于您需要它的位置)
var server = require('../server').server;
由于您已将socket.io添加到响应对象,因此可以在服务中将其用作
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
res.io.emit("broadcast", "clients");
};