How to post method inside add the socket connections in node.js

纵饮孤独 提交于 2019-12-12 03:18:14

问题


    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');
                   //});
               }
           });

I am trying to store mongolab(db)one username and password statically to collect the mongolab into my actual coding to comapare from username and passowrd. Everything will be access correctly but I cannot add from the socket.io connections in post method.

How to add socket.io (on or emit) in post method?


回答1:


Move the io.connection out of app.post, and record the client in another variable

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

Then to emit message in the app.post as below,

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


来源:https://stackoverflow.com/questions/34960509/how-to-post-method-inside-add-the-socket-connections-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!