0

I'm working on a user login application, trying to io.sockets.emit("userLogin", "some msg"); when some is logged in, somehow the server can't recieve the message.

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

Client 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

Funny thing is I have another emit in a app.get() function and the client side code is similar, that works. So I'm suspecting it's something to do with this app.post()? Any help is appreciated, thanks in advance!

4

1 回答 1

0

提交表单会触发页面重新加载,从而断开 socket.io。您应该使用event.preventDefault来避免这种情况。

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

  $.post("/sessions", {
    time: (new Date).toLocaleTimeString(),
    date: (new Date).toLocaleDateString()
  });
});
于 2012-08-07T08:32:27.930 回答