Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use express response to stay in the same page without redirect?

Consider a simple form which takes email as input. Submit button calls a bootstrap modal in case authentication failed. If at success, it redirects to the next view.

When bootstrap modal appears, the browser is constantly loading the page, waiting a response.

I am using this code on server side:

app.post('/', (req, res) => {
    Users.findOne({
        email: req.body.email
    })
    .then(user => {
        if (user) {
            obj = req.body.email
            res.redirect('/survey')
        }
    })
})

I tried to add an else statement in case user is not found:

...
else  {
  console.log('User not found')
  return
}

I do not want to redirect to the same page because modal will not work.

Is there a res method in order to achieve this?

like image 510
Ramiro Tormenta Avatar asked Jan 04 '18 19:01

Ramiro Tormenta


People also ask

How do I stay on the same page after the POST request?

How do you stay in the same page after submit a form in HTML? In order to stay on the same page on submit you can leave action empty ( action=”” ) into the form tag, or leave it out altogether. For the message, create a variable ( $message = “Success!

What does res redirect do?

The res. redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code.

How do I reroute Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.


1 Answers

The proper solution will be to use ajax for submitting form data & handling response

based on the response success / failure, you can redirect user or show modal for error from client side

If you still want to do it without ajax submission of form, you can redirect user to same url with adding querystring

res.redirect('/same-path?error=user_not_found') 

And check query params on load of page in client javascript

$(document).ready ( function(){
    var url = window.location.search;
    var queryStr = url.split("?")[1];

    if(queryStr) {
        let hash = queryStr.split('&);
        for (var i = 0; i < hash.length; i++) {
            params=hash[i].split("=");
            if(params[0] == 'error' && params[1] == 'user_not_found') {
                // SHOW YOUR MODAL HERE
            }
        }
    }
});​
like image 80
Sarfraaz Avatar answered Nov 01 '22 15:11

Sarfraaz