Express Request/Response Objects

Express is a powerful and flexible web framework built on top of Node.js, making it easier to handle web requests and responses. The heart of every Express application lies in the **request** (`req`) and **response** (`res`) objects. These objects serve as the backbone of how servers receive data from clients and send data back in return.

Understanding the Request Object (req)

Think of an Express request (`req`) object as a package sent by a customer to a store. This package contains important information, such as the type of request (GET, POST, etc.), query parameters, URL parameters, and any data the customer has sent. The store (server) then processes this package and decides how to respond.

Getting Data from Requests

The `req` object provides several ways to extract useful data from an incoming request. Here are some of the most commonly used properties:

req.body – Receiving Data from Clients

The `req.body` property allows you to access the data sent in the body of a request, typically from a form submission or API request.


// Client sending a request
fetch('http://localhost:4000/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ firstName: 'John', lastName: 'Adams' })
});
    

On the server, we can process this request using:


const express = require('express');
const app = express();

// Enable JSON body parsing middleware
app.use(express.json());

app.post('/users', (req, res) => {
    console.log(req.body);
    res.send('Data received');
});
    

When the client sends data in JSON format, Express automatically parses it into `req.body` so we can work with it as a JavaScript object.

req.query – Handling Query Parameters

Query parameters allow clients to send additional information in the URL using key-value pairs. They are commonly used for filtering, searching, or paginating results.

Example: If a client requests:

http://localhost:4000/users?firstName=John&lastName=Adams

The server can retrieve these values using:


app.get('/users', (req, res) => {
    console.log(req.query.firstName); // Output: John
    console.log(req.query.lastName);  // Output: Adams
    res.send('Query parameters received');
});
    

req.params – Handling URL Parameters

URL parameters allow us to define placeholders in routes to capture specific data.

Example: If a client makes a request to:

http://localhost:4000/users/John/Adams

The server can extract values from the URL like this:


app.get('/users/:firstName/:lastName', (req, res) => {
    console.log(req.params.firstName);  // Output: John
    console.log(req.params.lastName);   // Output: Adams
    res.send(`Hello, ${req.params.firstName} ${req.params.lastName}`);
});
    

Understanding the Response Object (res)

The response (`res`) object is how the server sends data back to the client. Think of it as the store sending a package back to the customer, containing everything they need.

Sending Responses with res.send()

The `res.send()` method is used to send simple responses, such as text or HTML.


app.get('/greet', (req, res) => {
    res.send('Hello, welcome to our API!');
});
    

Sending JSON Responses with res.json()

When sending structured data, `res.json()` is the preferred method, as it automatically sets the correct content type.


app.get('/user', (req, res) => {
    res.json({ firstName: 'John', lastName: 'Doe' });
});
    

Setting HTTP Status Codes with res.status()

Status codes provide information about the success or failure of a request. Express makes it easy to set status codes before sending responses.


app.get('/users', (req, res) => {
    try {
        res.status(200).json([{ firstName: 'John', lastName: 'Adams' }]);
    } catch (error) {
        res.status(500).send('Internal Server Error');
    }
});
    

Real-World Applications

The `req` and `res` objects are essential building blocks for modern web applications. Here’s how they are commonly used:

Common Mistakes to Avoid

What You’ve Learned

The request (`req`) and response (`res`) objects in Express provide a powerful and simple way to handle HTTP requests and responses. Understanding how to extract data from `req` and how to send meaningful responses using `res` is fundamental for building APIs and web applications.

By mastering these concepts, you'll be well-equipped to create robust web applications, interact with databases, and build APIs that serve dynamic content to users.