HTTP Request Methods in Node.js
Learn how HTTP request methods work in Node.js, how clients communicate with servers, and how to handle GET, POST, PUT, PATCH and DELETE requests using the built-in HTTP module.
HTTP request methods describe the type of operation a client wants to perform on a server. For example, at CIIT Training Institute, Samadhan may want to view student details, Pradnya may want to register a new student, and an administrator may need to update or delete a student record.
Node.js provides the built-in http module.
Inside the request callback, we can access
req.method and req.url to identify
the incoming request and decide how the server should respond.
1. What Are HTTP Request Methods?
HTTP request methods are used by clients to tell a server what operation they want to perform. A client can be a browser, a frontend application, Postman or another server.
For example, when Samadhan opens a student list, the client can send a GET request. When Pradnya submits a registration form, the client can send a POST request.
| Method | Purpose | Example |
|---|---|---|
GET |
Retrieve or read data. | View student details. |
POST |
Submit data or create a resource. | Register a new student. |
PUT |
Replace an existing resource. | Replace all editable student fields. |
PATCH |
Update selected fields. | Change only a student's course. |
DELETE |
Remove a resource. | Delete a student record. |
2. Why Are HTTP Methods Used?
Different methods help clients and servers communicate the intended operation clearly. They also make API routes easier to understand and maintain.
| Scenario | HTTP Method | Expected Operation |
|---|---|---|
| Samadhan views all students. | GET |
Return student information. |
| Pradnya registers a student. | POST |
Create a student record. |
| An administrator replaces student details. | PUT |
Replace the editable resource fields. |
| An administrator changes a student's course. | PATCH |
Update only the specified field. |
| An administrator removes a student. | DELETE |
Delete the selected record. |
3. How Do HTTP Request Methods Work?
The client sends an HTTP request containing a method and a URL. The Node.js server examines the request, performs the required operation and sends an HTTP response.
1. Client
Browser, Postman or frontend application
2. HTTP Request
Method: GET, POST, PUT, PATCH or DELETE
URL: /students
3. Node.js HTTP Server
Checks req.method and req.url
4. Perform Operation
Read, create, replace, update or delete data
5. HTTP Response
Status code, headers and response body
4. Checking the HTTP Method in Node.js
Node.js provides the req.method property to
identify the HTTP method used by the client. The
req.url property contains the requested URL.
We can use an if...else statement to check the
method and execute the appropriate code.
Basic Syntax
const http = require("node:http");
const server = http.createServer((req, res) => {
console.log("Request Method:", req.method);
console.log("Request URL:", req.url);
res.end("Request received");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Understanding the Code
| Code | Meaning |
|---|---|
require("node:http") |
Loads Node.js's built-in HTTP module. |
http.createServer() |
Creates an HTTP server. |
req.method |
Provides the HTTP method of the incoming request. |
req.url |
Provides the requested URL. |
res.end() |
Finishes the HTTP response. |
server.listen(3000) |
Starts listening on port 3000. |
Expected Terminal Output
Server running on port 3000
Request Method: GET
Request URL: /
Explanation:
When we open http://localhost:3000 in a browser,
the browser sends a GET request. The server prints the method
and URL in the terminal and sends the response text.
5. GET Method in Node.js
The GET method is used to retrieve information from a server. It is commonly used to display records, fetch product details or read student information.
For example, Samadhan wants to see the student details available at CIIT Training Institute. The client sends a GET request to the server.
Example: GET Request
const http = require("node:http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (req.method === "GET" && req.url === "/students") {
const students = [
{ id: 1, name: "Samadhan", course: "Node.js" },
{ id: 2, name: "Pradnya", course: "JavaScript" }
];
res.writeHead(200);
res.end(JSON.stringify(students));
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Test the Request
GET http://localhost:3000/students
Expected Output
[
{
"id": 1,
"name": "Samadhan",
"course": "Node.js"
},
{
"id": 2,
"name": "Pradnya",
"course": "JavaScript"
}
]
Explanation:
The server checks whether the method is GET and the URL is
/students. If both conditions match, it returns
the student list with status code 200.
6. POST Method in Node.js
The POST method is commonly used to submit data to a server or create a new resource. For example, Pradnya submits a registration form to add a student to the system.
Data is often sent in the request body. In Node.js, the incoming request body is a stream, so the server can collect its chunks and process the body when the request ends.
Example: POST Request
const http = require("node:http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (req.method === "POST" && req.url === "/students") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const student = JSON.parse(body);
if (
typeof student.name !== "string" ||
!student.name.trim() ||
typeof student.course !== "string" ||
!student.course.trim()
) {
res.writeHead(400);
res.end(JSON.stringify({
message: "Name and course are required"
}));
return;
}
res.writeHead(201);
res.end(JSON.stringify({
message: "Student registered successfully",
student: {
name: student.name.trim(),
course: student.course.trim()
}
}));
} catch {
res.writeHead(400);
res.end(JSON.stringify({
message: "Invalid JSON body"
}));
}
});
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Request Body
{
"name": "Pradnya",
"course": "Node.js"
}
Expected Response
{
"message": "Student registered successfully",
"student": {
"name": "Pradnya",
"course": "Node.js"
}
}
Explanation:
The server collects the incoming body using the
data and end events. It then parses
the JSON and validates the fields. Status code 201 indicates
successful creation in this illustrative example.
7. PUT Method in Node.js
The PUT method is generally used to create or replace a resource at a specified URL. When replacing an existing resource, the client normally sends all the fields needed for that resource.
For example, an administrator wants to replace the editable details of student number 1.
Example: PUT Request
const http = require("node:http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (req.method === "PUT" && req.url === "/students/1") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const student = JSON.parse(body);
if (
typeof student.name !== "string" ||
!student.name.trim() ||
typeof student.course !== "string" ||
!student.course.trim()
) {
res.writeHead(400);
res.end(JSON.stringify({
message: "Name and course are required"
}));
return;
}
const updatedStudent = {
id: 1,
name: student.name.trim(),
course: student.course.trim()
};
res.writeHead(200);
res.end(JSON.stringify({
message: "Student details replaced successfully",
student: updatedStudent
}));
} catch {
res.writeHead(400);
res.end(JSON.stringify({
message: "Invalid JSON body"
}));
}
});
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Request Body
{
"name": "Samadhan",
"course": "Advanced Node.js"
}
Explanation: The server accepts the complete editable student details, validates the values and constructs a replacement resource. This example returns the replacement in the response; it does not persist it to a database.
8. PATCH Method in Node.js
The PATCH method is used to update only selected fields of a resource instead of replacing the entire resource.
For example, Pradnya wants to change her course from JavaScript to Node.js without changing her name or ID.
Example: PATCH Request
const http = require("node:http");
const student = {
id: 2,
name: "Pradnya",
course: "JavaScript"
};
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (req.method === "PATCH" && req.url === "/students/2") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const updates = JSON.parse(body);
const allowedFields = ["name", "course"];
const fields = Object.keys(updates);
if (
!updates ||
typeof updates !== "object" ||
Array.isArray(updates) ||
fields.length === 0 ||
fields.some(field => !allowedFields.includes(field))
) {
res.writeHead(400);
res.end(JSON.stringify({
message: "Provide valid name or course fields"
}));
return;
}
for (const field of fields) {
if (
typeof updates[field] !== "string" ||
!updates[field].trim()
) {
res.writeHead(400);
res.end(JSON.stringify({
message: field + " must be a non-empty string"
}));
return;
}
}
for (const field of fields) {
student[field] = updates[field].trim();
}
res.writeHead(200);
res.end(JSON.stringify({
message: "Student details updated successfully",
student: student
}));
} catch {
res.writeHead(400);
res.end(JSON.stringify({
message: "Invalid JSON body"
}));
}
});
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Request Body
{
"course": "Node.js"
}
Expected Response
{
"message": "Student details updated successfully",
"student": {
"id": 2,
"name": "Pradnya",
"course": "Node.js"
}
}
Explanation: Only the supplied course field changes. The ID and name remain unchanged. In this example, the update affects an in-memory object and resets when the server restarts.
9. DELETE Method in Node.js
The DELETE method is used to request removal of a resource. For example, an administrator may want to delete a student record from the system.
Example: DELETE Request
const http = require("node:http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json; charset=utf-8");
if (req.method === "DELETE" && req.url === "/students/2") {
res.writeHead(200);
res.end(JSON.stringify({
message: "DELETE request received for student 2"
}));
} else {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Test the Request
DELETE http://localhost:3000/students/2
Expected Response
{
"message": "DELETE request received for student 2"
}
Explanation: This example demonstrates how to recognize a DELETE request. It does not actually delete a student because it does not use a database or a stored collection. A real DELETE handler must locate and remove the resource before returning success.
10. Difference Between GET, POST, PUT, PATCH and DELETE
| Method | Reads Data | Sends Body Commonly | Main Purpose |
|---|---|---|---|
GET |
Yes | Usually no | Retrieve data. |
POST |
Not its main purpose | Often yes | Submit data or create a resource. |
PUT |
Not its main purpose | Often yes | Create or replace a resource. |
PATCH |
Not its main purpose | Often yes | Partially update a resource. |
DELETE |
Not its main purpose | Usually no | Delete a resource. |
Note: Request bodies are not universally required or forbidden for every method. Follow the API's documented behavior.
11. Request Method Decision Flow
A Node.js server can check the request method and URL and then execute the matching route handler.
req.method and req.url
Read data
Create or submit data
Replace or update data
Remove a resource
Appropriate status code, headers and response body
12. How to Run a Node.js HTTP Program
- Install Node.js on your computer.
-
Create a file named
server.js. - Copy one example into the file.
- Open the terminal in that folder.
-
Run
node server.js. - Send the request using a browser or Postman, depending on the method being tested.
Terminal Command
node server.js
Expected Output
Server running on port 3000
Important Points
-
req.methodidentifies the incoming HTTP method. -
req.urlidentifies the requested URL. - GET is commonly used to retrieve data.
- POST is commonly used to submit data or create resources.
- PUT generally replaces a resource, while PATCH updates selected fields.
- DELETE requests removal of a resource.
- Validate incoming data and send an appropriate status code.
Summary
In this lesson, we learned how HTTP request methods work in Node.js using the built-in HTTP module. We explored how to identify incoming requests using req.method and req.url, and studied GET, POST, PUT, PATCH and DELETE through practical examples. These methods help clients communicate their intended operations to a server and form an important foundation for building HTTP APIs.