Using .emit from POST

こ雲淡風輕ζ 提交于 2019-12-02 10:58:50
Smitha

I don't think that there is a way to do this without using io.sockets.on('connection') again. If you're using res.render anyway, you could pass data through that though:

res.render('login', {msg: 'You have entered an invalid user / password!<br>Try Again.'});

and then do something like this in your jade doc to print out the message if it exists:

- if (msg)
     p #{msg}

But the problem with doing that is that it reloads the page, which I don't think you want if you're just trying to display a simple feedback message. You could use jQuery to submit the form on the client side instead:

    $('#myForm').submit(function(e){
        e.preventDefault();
        $.post(
            $(this).attr("action"), // The URL to send form data to
            $(this).serialize(), // Serializes the form data to be sent
            // Success callback function
            function(data){ 
                if(data.url){
                    window.location.href = data.url;
                } else{
                    $('#msg').html(data.msg);
                }
            }
        );
    });

On the server-side you would have:

app.post('/login', function(req, res){
    // do whatever you need to check if the login is valid
    if(validLogin){
        res.send({url: myURL}); // send url that user should be redirected to
    } else{
        res.send({msg: 'You have entered an invalid user / password!<br>Try Again.'});
    }
});

So if the login is valid, the URL to redirect is sent back to the browser and the user is redirected. If the login is not valid, the error message is sent back and is displayed. Check out this question for more about submitting a form and then redirecting via jQuery.

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