Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send error message on redirect

I have a login form /login that posts the login info to /checklogin. If the credentials are incorrect, I want to redirect the user to /login with an error message along the lines of "incorrect username or password". However, I can't seem to figure out how to pass an option through res.redirect like you would using res.render.

What's the best way of doing this? I saw a prior question asked about this, but it doesn't seem to work in the later versions of Express.

like image 246
Jonathan Hwa Avatar asked Nov 05 '13 20:11

Jonathan Hwa


2 Answers

With a redirect alone, it's not really possible to pass options other than in the query-string:

res.redirect('/login?e=' + encodeURIComponent('Incorrect username or password'));

A redirect instructs the client to start a new request and HTTP is on its own stateless.

To keep the message otherwise, you'll need a form of persistence to hold it for that next request -- cookies, sessions, etc.

req.session.error = 'Incorrect username or password';
res.redirect('/login');

Then:

res.render('login', { error: req.session.error });
delete res.session.error; // remove from further requests

This is also what Express 2's req.flash() helped accomplish. And, a variant of it is still available for use with Express 3 and later -- just as connect-flash rather than being bundled.

like image 54
Jonathan Lonowski Avatar answered Oct 20 '22 09:10

Jonathan Lonowski


Server side:

res.redirect('/login?error=' + encodeURIComponent('Incorrect_Credential'));

In view there will be a alert (Hope you guys are using bootstrap). But initially it will be hide. If error comes, it will be shown.

<div class="alert alert-success" role="alert" id="loginAlert">
    <p style="text-align: center;">Incorrect Credential</p>
</div>

Showing Technique:

<script>
    $('#loginAlert').hide();
    const urlParams = new URLSearchParams(window.location.search);
    const myParam = urlParams.get('error');
    if(myParam == "Incorrect_Credential") {
        $('#loginAlert').show();
    }
</script>
like image 33
Rajan saha Raju Avatar answered Oct 20 '22 08:10

Rajan saha Raju