DEV Community

Pravin Jadhav
Pravin Jadhav

Posted on

Understanding Request and Response in Node.js Backend

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'));
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

Server Response:

HTTP/1.1 200 OK  
Content-Type: application/json  

{
    "id": 1,
    "name": "John Doe"
}
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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...!!!!

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay