如何发布方法在node.js中添加套接字连接

时间:2016-01-23 06:45:07

标签: node.js mongodb chat

    var admins = db.collection('admin');
    app.post('/form-data', urlencodedParser, function (req, res) {
           response = {
               Username: req.body.Username,
               Password: req.body.Password
           };
           console.log(response);
           var exists = false;
           admins.find().toArray(function (err, key) {
               var length = key.length;
               if (key[0].username.toLowerCase() === req.body.Username.toLowerCase() && key[0].password.toLowerCase() === req.body.Password.toLowerCase())
               {
                   res.redirect('/chat/');
                   app.get('/chat/', function (req, res) {
                       res.render('chat');
                   });
               }
               else
               {

                   res.redirect('/');
                   app.get('/', function (req, res) {
                       res.render('index');
                       console.log("palanivelm");
                       socket.emit('messages', 'username & password is incorrect');
                   });
                   //io.on('connection', function(client) {
                   //   console.log('Client connected...');
                   //   client.emit('messages', 'username & password is incorrect');
                   //});
               }
           });

我正在尝试静态存储mongolab(db)一个用户名和密码,以便将mongolab收集到我的实际编码中,以便从username和passowrd进行comapare。一切都将正确访问,但我不能从post方法中的socket.io连接添加。

如何在post方法中添加socket.io(on或emit)?

1 个答案:

答案 0 :(得分:0)

io.connection移出app.post,并将客户端记录在另一个变量

var ioClient = null;
io.on('connection', function(client) {
      console.log('Client connected...');
      ioClient = client;
});

然后转到emit中的app.post消息,如下所示

app.post('/form-data', urlencodedParser, function (req, res) {
     ...
     // handling socket.io
     if (ioClient)
        ioClient.emit('messages', 'username & password is incorrect');             
});