ExpressJS : res.redirect() not working as expected? ExpressJS : res.redirect() not working as expected? express express

ExpressJS : res.redirect() not working as expected?


The problem might not lie with the backend, but with the frontend. If you are using AJAX to send the POST request, it is specifically designed to not change your url.

Use window.location.href after AJAX's request has completed (in the .done()) to update the URL with the desired path, or use JQuery: $('body').replaceWith(data) when you receive the HTML back from the request.


If you are using an asynchronous request to backend and then redirecting in backend, it will redirect in backend (i.e. it will create a new get request to that URL), but won't change the URL in front end.

To make it work:

  1. use windows.location.href = "/url"
  2. change your async request (in front end) to simple anchor tag (<a></a>)


It's almost certain that you are making an async call to check Mongoose but you haven't structured the code so that the redirect only happens after the async call returns a result.

In javascript, the POST would look like something this:

function validateCredentials(user, callback){    // takes whatever you need to validate the visitor as `user`    // uses the `callback` when the results return from Mongoose}app.post('/credentials', function(req, res){    console.log("Here was are: '/credentials'";    validateCredentials(userdata, function(err, data){        if (err) {            // handle error and redirect to credentials,            // display an error page, or whatever you want to do here...        }        // if no error, redirect        res.redirect('/');    };};

You can also see questions like Async call in node.js vs. mongoose for parallel/related problems...