Understand Client Request in Node.
What is a Client Request?
A client request is the action performed by the client (browser or any API testing tool) when it tries to access a URL or send data to the server.
Whenever you open a website or call an API, you're sending a request to the server, and in return, the server sends a response.
Code to Access Client Request
const http = require("http");
http
.createServer((req, resp) => {
console.log(req.url); // Log the requested URL
console.log(req.headers); // Log the request headers
console.log(req.headers.host); // Log the host
console.log(req.method); // Log the HTTP method (GET, POST, etc.)
})
.listen(5000);
Now open localhost:5000/
, and check the terminal — you’ll see the request data being logged.
Make Pages with Client Request
const http = require("http");
http
.createServer((req, resp) => {
if (req.url == "/") {
resp.write("<h1>Home page</h1>");
} else if (req.url == "/login") {
resp.write("<h1>Login page</h1>");
} else {
resp.write("<h1>Other page</h1>");
}
resp.end(); // End the response
})
.listen(5000);
How to Test It?
Run the file:
nodemon filename.js
Open your browser:
http://localhost:5000/
→ Shows Home pagehttp://localhost:5000/login
→ Shows Login page- Any other route → Shows Other page