Handling Requests in Node.js
In Node.js, handling requests means receiving an HTTP request from a client, examining its URL, HTTP method and headers, and deciding how the server should respond.
1. What is Request Handling?
When a browser opens a website, it sends an HTTP request to the server.
The server receives that request and processes it using the request
handler registered with http.createServer().
For example, Samadhan opens the CIIT Training Institute website. Pradnya's Node.js server receives the request and checks which page Samadhan wants to access before sending the appropriate response.
2. Understanding the Request Object
The request object, usually named req, contains information
about the incoming HTTP request.
| Property | Description | Example |
|---|---|---|
req.url |
Provides the request URL path and query string. | /courses |
req.method |
Provides the HTTP method. | GET |
req.headers |
Contains the request headers. | host, accept |
req.headers["content-type"] |
Reads the content type header when supplied. | application/json |
3. Displaying Request Information
We can display the URL, HTTP method, and headers of an incoming request using the request object.
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Request URL:", req.url);
console.log("Request Method:", req.method);
console.log("Request Headers:", req.headers);
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Request received successfully!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Terminal Output
Server running at http://localhost:3000 Request URL: / Request Method: GET Request Headers: [request header object]The header object contains actual values supplied by your browser. Additional requests may appear in the terminal.
Browser Output
Explanation
req.urltells us the requested path.req.methodtells us which HTTP method was used.req.headerscontains metadata sent by the client.res.end()sends the response and completes the request's response.
4. Request Handling Flow
5. Handling Different URLs
A server can respond differently depending on the requested URL. This is a simple form of manual routing using Node.js's built-in HTTP module.
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
if (req.url === "/") {
res.end("Welcome to CIIT Training Institute!");
} else if (req.url === "/courses") {
res.end("Available courses: Java, Python, .NET and Node.js");
} else if (req.url === "/about") {
res.end("Learn more about CIIT Training Institute.");
} else {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("404 - Page Not Found");
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
writeHead(200) sends
the headers before the 404 branch. For a correct 404 response,
set the status inside each route before sending the body.
Use the corrected version below.
Corrected Code
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
if (req.method !== "GET") {
res.writeHead(405);
res.end("405 - Method Not Allowed");
} else if (req.url === "/") {
res.writeHead(200);
res.end("Welcome to CIIT Training Institute!");
} else if (req.url === "/courses") {
res.writeHead(200);
res.end("Available courses: Java, Python, .NET and Node.js");
} else if (req.url === "/about") {
res.writeHead(200);
res.end("Learn more about CIIT Training Institute.");
} else {
res.writeHead(404);
res.end("404 - Page Not Found");
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Try These URLs
| URL | Expected Response | Status |
|---|---|---|
http://localhost:3000/ |
Welcome to CIIT Training Institute! | 200 |
http://localhost:3000/courses |
Available courses: Java, Python, .NET and Node.js | 200 |
http://localhost:3000/about |
Learn more about CIIT Training Institute. | 200 |
http://localhost:3000/contact |
404 - Page Not Found | 404 |
6. Handling Query Strings
A URL may contain query parameters. For example,
/student?name=Samadhan contains the path
/student and the query parameter name.
We can use Node.js's URL class to parse them.
const http = require("http");
const server = http.createServer((req, res) => {
const requestUrl = new URL(
req.url,
"http://localhost:3000"
);
if (requestUrl.pathname === "/student") {
const name = requestUrl.searchParams.get("name") || "Student";
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Welcome, " + name + "!");
} else {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Page Not Found");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Test URL
http://localhost:3000/student?name=Samadhan
Browser Output
Explanation
new URL()parses the request URL.pathnamegives the path, such as/student.searchParams.get("name")reads the name query parameter.- The server uses the name to construct its response.
7. Handling Different HTTP Methods
The HTTP method indicates the kind of operation the client wants to perform. Common methods include GET, POST, PUT, and DELETE.
| Method | Typical Purpose |
|---|---|
GET |
Retrieve information. |
POST |
Submit data or create a resource. |
PUT |
Create or replace a resource at a known URI, depending on the API. |
DELETE |
Request removal of a resource. |
For this lesson, we will handle GET requests and return a 405 status for other methods.
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
if (req.method === "GET") {
res.writeHead(200);
res.end("GET request received successfully.");
} else {
res.writeHead(405);
res.end("Only GET requests are supported.");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Expected Response for a GET Request
Expected Response for Another Method
8. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Checking only the URL and ignoring the HTTP method. | Check both req.url and req.method when needed. |
| Sending a 200 status for an unknown route. | Return 404 when the requested resource is not found. |
| Comparing a complete URL directly when query strings are present. | Parse the URL and compare pathname. |
Trying to send another response after res.end(). |
Send one completed response for each request. |
| Trusting query parameter values without validation. | Validate and safely handle client-provided input. |
9. Important Points to Remember
reqcontains information about the incoming request.req.urlprovides the request URL.req.methodprovides the HTTP method.req.headerscontains request headers.- The URL class can parse paths and query parameters.
- Use appropriate status codes such as 200, 404, and 405.
- Complete each response with
res.end().
Summary
In this lesson, we learned how to inspect incoming HTTP requests, read URL paths and methods, handle different routes, parse query parameters, and return suitable status codes. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how a Node.js server can respond to different client requests.