The following is an MCVE of my server.js
code:
let fs = require('fs');
let http = require('http');
http.createServer((req, res) => {
// Handles GET requests
if(req.method == 'GET') {
let file = req.url == '/' ? './index.html': '/login.html'; // just an example
fs.readFile(file, (err, data) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
}
// Handles POST requests
else {
read(status => {
if(status) {
res.writeHead(302, {
'Location': 'http://localhost:8000/login.html',
'Content-Type': 'text/html'
});
res.end();
console.log('Redirected!');
}
});
}
}).listen(8000);
// In my actual script, the `read` function reads JSON files and sends data,
// so I've used the callback function
let read = callback => fs.readFile( './index.html', (err, data) => callback(true) );
And, I've two HTML files as mentioned inside the code.
index.html
<input type="submit" onclick='let xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:8000"); xhr.send();'>
I've used inline script to minimize traffic in my MCVE. For development purposes, I'll be using external scripts on my website
login.html
<h1>Login</h1>
Now, when I open http://localhost
, index.html
shows up nicely. As you've noticed that index.html
is just a button. So, when I click on that button, Ajax request is fired successfully and everything works fine (no console errors) EXCEPT the fact that page does not redirects. I don't know what it going wrong or what else is missing.
I'm a beginner in Node.js and read about redirection in Nodejs - Redirect url and How to redirect user's browser URL to a different page in Nodejs?, I've searched a lot but couldn't get a hint on this. Thanks for your time!
Also, I'm aware about express, but I don't consider use of frameworks as they hide core concepts.
EDIT: When I try redirecting without the callback concept, then it works fine, as this video tells us.