需要套接字服务器到控制器

时间:2015-02-20 20:50:14

标签: javascript node.js express socket.io

所以基本上我试图用MVC结构设置我的节点(快速)项目。问题是当我需要在我的任何控制器中需要套接字的实例时,因为我总是未定义。知道如何改进这段代码吗?

// server.js

var express = require('express');
var socketio = require('socket.io');

var homeController = require('./controllers/home');

var app = express();

app.post('/api/chat/messages/:room', homeController.postChatMessages);

var server = app.listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

var io = socketio.listen(server);

module.exports = io;

// Controller home.js

var io = require('../server');
var Chat = require('../models/chat');

console.log(io); //GET UNDEFINED

exports.postChatMessages = function(req, res) {
Chat.findOne({ name: req.params.room }, function(err, chat) {
    if (chat) {
        chat.users._id = req.user;
        chat.messages.push({
            text: req.body.message
        });

        chat.save(function(err, saved) {
            if (err) {
                res.send(err);
                return console.log(err);
            }
            res.send(saved);
            io.sockets.emit('receiveMessage', saved);
        })
    }else{
        return res.status(400).send({ message: 'This chat room is not registered or maybe is not active.' });
    }
});
};

1 个答案:

答案 0 :(得分:-1)

您需要将控制器传递给正确的对象。您正在创建一个新对象,因此您没有正确的参考。这有一些可能性,我只会向你展示一个...我无法测试代码,但我猜你有这个想法。祝你好运

app.js中的

var homeController = require('./controllers/home')(io);
在home.js中你必须做更多的工作:

var HomeController = function(io){
  this.postChatMessages = function(req, res) {
    Chat.findOne({ name: req.params.room }, function(err, chat) {
      if (chat) {
        chat.users._id = req.user;
        chat.messages.push({
          text: req.body.message
        });

        chat.save(function(err, saved) {
          if (err) {
            res.send(err);
            return console.log(err);
          }
          res.send(saved);
          io.sockets.emit('receiveMessage', saved);
        });
      }else{
        return res.status(400).send({ message: 'This chat room is not registered or maybe is not active.' });
      }
    });
  };
}

module.exports = function(io){
  return new HomeController(io);
}