Redirecting using "pure" Node.js from inside a callback function Redirecting using "pure" Node.js from inside a callback function ajax ajax

Redirecting using "pure" Node.js from inside a callback function


This is not an issue with node.js. It is just how browsers behave.

Ajax (XHR) does not trigger redirects in the browser. When browsers implemented XHR browser developers assumed you want control of the page refresh behaviour. Therefore they made sure XHR does not trigger any default action. All redirects will be silent and the resultant data of the redirect will be passed to your XHR object's onreadystatechange callback.

If you want redirects to trigger page refresh you can simply choose to not use XHR. Instead do a form submission:

<!-- index.html --><form action="http://localhost:8000" method="post">    <input type="submit"></form>

If instead you want to use AJAX, you will need to do the redirect in the browser like I mentioned above:

// server.js// ...http.createServer((req, res) => {    // ...    // Handles POST requests    else {        read(status => {            if(status) {                res.writeHead(200, {'Content-Type': 'application/json'});                res.end(JSON.stringify({                    your_response: 'here'                }));            }        });    }}).listen(8000);

Then handle that response in the browser:

index.html

<input type="submit" onclick='let xhr = new XMLHttpRequest();xhr.addEventListener("load", function(){var response = JSON.parse(this.responseText);/* check response if you need it: */if (response.your_response === 'here') {window.location.href = 'http://localhost:8000/login.html';}});xhr.open("POST", "http://localhost:8000");xhr.send();'>

But this is crazy ugly and almost impossible to read. I'd suggest refactoring that HTML to something like this:

<!-- index.html --><script>    function handleSubmit () {      let xhr = new XMLHttpRequest();      xhr.addEventListener("load", function(){        var response = JSON.parse(this.responseText);        /* check response if you need it: */        if (response.your_response === 'here') {          window.location.href = 'http://localhost:8000/login.html'; // REDIRECT!!        }      });      xhr.open("POST", "http://localhost:8000");      xhr.send();    }</script><input type="submit" onclick="handleSubmit()">


You should be using express when dealing with node js web application unless you have an internal understanding of the current node version you are using a suggestion.

Express is simple and you code would look like this (and to redirect)

app.get('/index.html',function(req,res,next){   res.redirect('/path/to/redirect/file')}

link:http://expressjs.com/en/4x/api.html#res.redirect