if I go to the home page then I go to the contact page I go back again to the home page it says the site can’t be reached
var http = require("http");
http
.createServer(function (req, res) {
console.log(req.url);
const url = req.url;
if (url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.write("<h1 style = color:red>this is home</h1> <p>marzzuk</p>");
res.end();
}
if (url === "/contact") {
res.writeHead(200, { "Content-Type": "text/html" });
res.write("<h1 style = color:red>this is contact</h1>");
res.end();
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.write("<h1 style = color:red>404</h1>");
res.end();
}
})
.listen(8080);
>Solution :
This is a simple logic issue.
If the URL is / then both the first if and the else condition are true with the latter trying to write to the response after it has been ended.
Isolate your logic branches to avoid crashing the server
switch (url) {
case "/":
res.writeHead(200, { "Content-Type": "text/html" });
res.write(`<h1 style="color:red">this is home</h1> <p>marzzuk</p>`);
return res.end();
case "/contact":
res.writeHead(200, { "Content-Type": "text/html" });
res.write(`<h1 style="color:red">this is contact</h1>`);
return res.end();
default:
res.writeHead(404, { "Content-Type": "text/html" });
res.write(`<h1 style="color:red">404</h1>`);
return res.end();
}

