Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

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

    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...