Reputation: 1
I am using vanilla node without any framework and I can't seem to redirect to another page.So far I have tried
const server = require('http');
server.createServer(
function (req, res) {
if (req.url == '/') {
// do stuff
res.end();
}
else if (req.url == '/signIn') {
res.writeHead(302, { Location: '/signIn' });
res.end();
}
}).listen(8080);
I have also used 301 but to no avail. I can easily read from the file and display it's contents like so
const server = require('http');
const fileSys = require('fs');
fileSys.readFile('./signIn.html', function (err, html) {
server.createServer(function (req, res) {
if (req.url == '/') {
//do something
}
else if (req.url == '/signIn') {
res.writeHead(200, { 'content-type': 'text/html'});
res.write(html);
res.end();
}
})
.listen(8080);
});
But I don't want that. I have seen that it can be done easily with help of express. Is vanilla node not right tool for routing? "signin" is a simple html file
<!DOCTYPE html>
<html>
<body background="blue">
<h1>Sign In here!</h1>
<p>Enter your Information</p>
</body>
</html>
Upvotes: 0
Views: 160
Reputation: 510
This should work, did you test if the req.url is actually '/signIn'? Also it would be better to use '===' instead of '==' so that you check for the specific type of the attribute.
Try to add a console.log, or use a debugger and let me know.
edit: I've tested your code locally and it seems to work fine? I'm not sure what you're expecting here. What happens when I open a page in my browser it sees the req.url as "/" so it does nothing which is what you've coded. When I navigate to /signIn it opens the html page. You could add an else statement that also does the same as in the 'else if (req.url == '/signIn') ' ?
Upvotes: 0