In a Node.js backend, the request (req) and response (res) objects are used to handle communication between the client (browser, mobile app, etc.) and the server. These objects are part of the HTTP module or frameworks like Express.js.
1️⃣ What is a Request (req)?
A request is sent by the client to the server asking for some action, like fetching data, submitting a form, or updating a resource.
Request Components:
✔ Method – Defines the type of action (GET, POST, PUT, DELETE).
✔ URL/Path – The endpoint being requested (/users
, /login
, etc.).
✔ Headers – Extra information (Auth tokens, content type, etc.).
✔ Body – Data sent by the client (JSON, form data, etc.).
✔ Query Parameters – Additional data in the URL (?id=123&name=John
).
Example: Handling a Request in Express.js
const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON request body
app.post('/login', (req, res) => {
console.log(req.method); // "POST"
console.log(req.url); // "/login"
console.log(req.headers); // Headers sent by client
console.log(req.body); // { "username": "JohnDoe", "password": "1234" }
res.send('Login request received');
});
app.listen(3000, () => console.log('Server running on port 3000'));
2️⃣ What is a Response (res)?
A response is the server's reply to a client request. It contains the data or message that the client expects.
Response Components:
✔ Status Code – HTTP status (200 for success, 404 for not found, etc.).
✔ Headers – Extra response details (like content type).
✔ Body – The actual response data (JSON, HTML, etc.).
Example: Sending a Response in Express.js
app.get('/user', (req, res) => {
const user = { id: 1, name: "John Doe" };
res.status(200) // Set status code to 200 (OK)
.json(user); // Send JSON response
});
3️⃣ Request-Response Flow Example
📌 When a client makes a request, the server processes it and sends back a response:
Client Request:
GET /user?id=1 HTTP/1.1
Host: example.com
Content-Type: application/json
Server Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"name": "John Doe"
}
4️⃣ Common Request-Response Methods in Express.js
Method | Purpose | Example API Endpoint |
---|---|---|
GET | Fetch data from the server | /users |
POST | Send data to the server | /register |
PUT | Update an existing resource | /users/1 |
DELETE | Remove a resource | /users/1 |
5️⃣ Middleware & Request Processing
Middleware functions in Express.js process requests before sending a response.
Example: Logging Middleware
app.use((req, res, next) => {
console.log(`[${req.method}] ${req.url}`);
next(); // Pass control to the next middleware or route
});
Conclusion
🔹 Request (req) contains the client’s data (method, URL, body, headers).
🔹 Response (res) is what the server sends back (status code, data).
🔹 Middleware helps process requests before sending responses.
🔹 Express.js makes request-response handling easy and structured.
Thanks Guys...!!!!
Top comments (0)