Home > Net >  Why this is happening on NodeJs
Why this is happening on NodeJs

Time:05-04

I am learning node js and when ever i run the code the code will run perfectly but when i change the url location then it will show the error

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.end(`<h1>This is Home Page</h1>`);
  }
  if (req.url === "/about") {
    res.end(`<h1>This is about Page</h1>`);
  }
  res.end(`
  <h1>Page not FOund</h1>
  <p> Would you like to go home page </p>
  <a href="/">Home Page</a>
  `);
});

server.listen(5000);

enter image description here

CodePudding user response:

Say you are accessing url / your res will call

res.end(`<h1>This is Home Page</h1>`);

and then

res.end(`
  <h1>Page not FOund</h1>
  <p> Would you like to go home page </p>
  <a href="/">Home Page</a>
`); 

According to the docs https://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback

Calling end with a string means passing the string to the Writable and then signals that no more data will be written into it. Writing anything after it will raise an error. So basically you need to make sure no moreend('someString') being called after another.

Fix using else if and else:

if (req.url === "/") {
  res.end(`<h1>This is Home Page</h1>`);
} else if (req.url === "/about") {
  res.end(`<h1>This is about Page</h1>`);
} else {
  res.end(`
  <h1>Page not FOund</h1>
  <p> Would you like to go home page </p>
  <a href="/">Home Page</a>
  `);
}
  

Or maybe use a switch

switch (res.url) {
  case '/':
    res.end(`<h1>This is Home Page</h1>`);
    break;
  case '/about':
    res.end(`<h1>This is about Page</h1>`);
    break;
  default:
    res.end(`
      <h1>Page not FOund</h1>
      <p> Would you like to go home page </p>
      <a href="/">Home Page</a>
    `);

CodePudding user response:

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    return res.end(`<h1>This is Home Page</h1>`);
  }
  if (req.url === "/about") {
    return res.end(`<h1>This is about Page</h1>`);
  }
  return res.end(`
  <h1>Page not FOund</h1>
  <p> Would you like to go home page </p>
  <a href="/">Home Page</a>
  `);
});

server.listen(5000);

In nodejs server, before you using res for end of route, u should have a return statement to end of routing, it's sometime have bug with duplicate return data

  • Related