DEV Community

entrepreneur123
entrepreneur123

Posted on

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 .

Top comments (0)