Request and Response in nodejs

entrepreneur123

entrepreneur123

Posted on June 16, 2022

Request and Response in nodejs

Hey !! this is Irusha and in this post you are gonna to learn about the request and response in nodejs and lets jump into code directly.

you got to create a views folder in which you will be creating about.html, home.html and 404.html and outside the folder you got to create server.js. And we will run the following code .Its simple and easy !! you gottta....

server.js

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  console.log(req.url, req.method);

  res.setHeader("Content-Type", "text/html");
  let path = "./views/";
  switch (req.url) {
    case "/":
      path += "index.html";
      break;
    case "/about":
      path += "about.html";
      break;
    default:
      path += "404.html";
      break;
  }
  fs.readFile(path, (err, data) => {
    if (err) {
      console.log(err);
      res.end();
    } else {
      //res.write(data);
      res.end(data);
    }
  });
});

server.listen(3000, "localhost", () => {
  console.log("listening to the 3000 local host");
});

Enter fullscreen mode Exit fullscreen mode

After that run above code as node server and hit enter then you will see output. And tried out going to localhost:3000 you will get result .

💖 💪 🙅 🚩
entrepreneur123
entrepreneur123

Posted on June 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related