Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

im learning backend route its all ok for first time but when i go back for the second time the site cant be reach

terminal

enter image description here

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading