【问题标题】:How to post method inside add the socket connections in node.js如何在node.js中添加套接字连接中的post方法
【发布时间】:2016-04-29 20:50:04
【问题描述】:
    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)one 用户名和密码,以将 mongolab 收集到我的实际编码中,以便与用户名和密码进行比较。一切都将正确访问,但我无法在 post 方法中从 socket.io 连接添加。

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

【问题讨论】:

    标签: node.js mongodb chat


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我已经在尝试使用这种方法来验证客户端中的用户名和密码不相等。使用在我的管理员登录页面中显示错误警报发出。但我正在刷新错误警报无法删除的页面管理页面。如何删除错误消息?
    • 刷新页面时,post是否重新发送到服务器?
    • 当您刷新页面时,将创建新的 Web 套接字。所以我猜想从客户端发送了一些额外的post 请求。
    • 当你刷新页面时,新的post请求将从客户端发送到服务器?如果是这样,我认为这不是好的设计。最好通过一个button 表单或其他方式从客户端发送post 请求..
    • 好的先生...让我知道我检查它。一些额外的post请求如何发送?
    猜你喜欢
    • 2018-11-22
    • 1970-01-01
    • 2015-03-25
    • 2014-05-11
    • 2013-04-05
    • 1970-01-01
    • 2022-09-30
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多