我想在我的nodejs项目中包含“ socket.io”。我将参数传递给 app.js 的路由,如下所示。
app.js :
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.emit('clients', { event:'connected', exData1: 'A', exData2: 'B' });
socket.on('server', function (data) {
console.log('Received data from client: ', data);
});
});
require('./routes/project')(router,io)
然后我已将其从路由转发到控制器。
routes / projects.js :
module.exports = (router,io) => {
const controller = require('./../controllers/project.ctrl')(io);
router.route('/projects/:id').get(controller.getProject)
...
}
我无法从自己的方法内部访问“ io”参数。
controllers / project.ctrl.js :
module.exports = (io) => {
var module = {};
// console.log('IO 1: ',io) // io is accessible in here
module.getProject = (req, res, next) => {
console.log('IO 2: ',io) // io is undefined in here :(
Project.findById(req.params.id).exec((err, project)=> {
if (err) res.send(err)
else if (!project) res.sendStatus(404)
else {
if (io) {
io.emit('clients', { event:'project_viewed' });
console.log('Emitted');
} else {
console.log('io not found :( !!!!!')
}
return res.send(project)
}
next()
})
}
...
return module;
}
如何从nodejs模块方法内部访问io参数?