2012-08-06 27 views
0

我工作的用戶登錄應用程序,試圖io.sockets.emit("userLogin", "some msg");io.sockets.emit當一些登錄,莫名其妙服務器無法收到該消息不發送味精服務器

服務器app.js:

app.post('/sessions', function(req, res) { 
user.authenticate(req.body.login, req.body.password, req.body.role, function(user) {  
    if (user) { 
     req.session.user = user; 
     console.log("correct"); 
     io.sockets.emit("userLogin", "some msg"); 
     res.redirect('/add_users');   
    } else { 
     console.log("wrong"); 
     res.render('sessions', {locals: { 
      redir: req.body.redir 
     }}); 
    }; 
}); 
}); 

客戶login.jade:

html 
head 
    script(src='jquery-1.7.1.js') 
    script(src='http://localhost:3002/socket.io/socket.io.js') 
    script(type='text/javascript') 
     var socket; 
     socket = io.connect('http://localhost:3002'); 
     socket.on('userLogin', function(user) { 
      console.log("userLogin: ", user) 
     }); 
     $(function() { 
      $("button").click(function() { 
       $.post("/sessions", { 
        time: (new Date).toLocaleTimeString(), 
        date: (new Date).toLocaleDateString() 
       }); 
      }); 
     }); 

body 
    h1 Login 
     form(action='/sessions', method='post') 
      input(type='hidden', name='redir', value='redir') 
      p 
       lable(for='login') Login: 
       input(type='text', name='login', id='login')   
      p 
       lable(for='password') Password: 
       input(type='text', name='password', id='password') 
      p 
       button Login 

有趣的是我還有一個發出的app.get()功能和客戶端代碼是相似的,那工作。所以我懷疑這與app.post()有什麼關係?任何幫助表示感謝,提前致謝!

+0

我懷疑它有什麼用POST。您確定在點擊按鈕時用戶已正確連接到Socket.IO服務器嗎?你有沒有嘗試過這個代碼與多個用戶(你是廣播畢竟)? – freakish 2012-08-06 14:22:14

+1

我認爲當你發佈你的表單時,頁面刷新並且socket.io連接斷開。 – 2012-08-06 16:36:36

+0

@Laurent Perrin:哦,你是對的,經過測試後,我也注意到了,我應該怎樣避免連接丟失? – nihulus 2012-08-07 07:04:20

回答

0

提交表單會觸發頁面重新加載,這將斷開socket.io的連接。您應該使用event.preventDefault來避免這種情況。

$("button").click(function(event) { 
    event.preventDefault(); 

    $.post("/sessions", { 
    time: (new Date).toLocaleTimeString(), 
    date: (new Date).toLocaleDateString() 
    }); 
}); 
相關問題