我相信我在Express应用程序的主文件(server.js)中正确设置了socket.io。如何从控制器访问socket.io以作为控制器操作的一部分发出事件?
我基于类似的帖子尝试了以下内容,但是我收到错误,说明套接字未定义。任何帮助将不胜感激。
同类文章: Socket.io emit from Express controllers
server.js:
'use strict';
var express = require('express'),
path = require('path'),
fs = require('fs'),
mongoose = require('mongoose'),
http = require('http'),
socketio = require('socket.io');
/**
* Main application file
*/
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./lib/config/config');
var db = mongoose.connect(config.mongo.uri, config.mongo.options);
// Bootstrap models
var modelsPath = path.join(__dirname, 'lib/models');
fs.readdirSync(modelsPath).forEach(function (file) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(modelsPath + '/' + file);
}
});
// Populate empty DB with sample data
require('./lib/config/dummydata');
// Passport Configuration
var passport = require('./lib/config/passport');
// Setup Express
var app = express();
// Setup socket.io
var server = http.createServer(app);
var io = socketio.listen(server);
require('./lib/config/express')(app);
require('./lib/routes')(app);
// Start server
// Call listen on server instead of app to setup socket.io. See this post:
// https://stackoverflow.com/questions/21173182/why-isnt-my-angularjs-express-socket-io-app-serving-the-socket-io-js-file/21175137#21175137
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env'));
});
io.sockets.on('connection', function(socket) {
console.log('socket connected');
socket.emit('message', {
message: 'You are connected to the backend through the socket!'
});
});
// Expose app
exports = module.exports = app;
routes.js:
'use strict';
var api = require('./controllers/api'),
index = require('./controllers'),
users = require('./controllers/users'),
items = require('./controllers/items'),
session = require('./controllers/session'),
middleware = require('./middleware');
/**
* Application routes
*/
module.exports = function(app, socket) {
app.route('/api/items')
.get(items.index)
.post(items.create(socket));
// All undefined api routes should return a 404
app.route('/api/*')
.get(function(req, res) {
res.send(404);
});
// All other routes to use Angular routing in app/scripts/app.js
app.route('/partials/*')
.get(index.partials);
app.route('/*')
.get( middleware.setUserCookie, index.index);
};
items.js(控制器):
'use strict';
var mongoose = require('mongoose'),
Item = mongoose.model('Item');
exports.create = function(socket) {
return function(req, res) {
// write body of api request to mongodb
socket.emit();
}
}