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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With