18

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.

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In the situation where you can't use res.render? like in the case of react-native app
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.