Request and Response in nodejs
entrepreneur123
Posted on June 16, 2022
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");
});
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
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
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024