ExpressJS Request & Response Handling: Powerful Guide 2025

Once you’ve grasped the fundamentals of middleware and routing in Express, the next crucial step is mastering ExpressJS request and response handling. At the core of every server interaction are two objects: the request (`req`) and the response (`res`). Understanding how to work with them is key to building anything from a simple API to a full-fledged web application.

This guide will walk you through reading incoming request data, sending various types of responses, serving static files, and even handling file uploads. Let’s get started!

Working with the Request Object (`req`)

The `req` object represents the incoming HTTP request and contains a wealth of information about it. You can access the URL, HTTP headers, request body, query parameters, and more. Let’s look at the most common properties you’ll use.

Reading Headers, Body, Params, and Query

  • `req.params`: Used to access route parameters, which are named segments of the URL. // For a route like /users/:id
    app.get('/users/:id', (req, res) => {
    const userId = req.params.id;
    res.send(`Fetching data for user ${userId}`);
    });
  • `req.query`: Contains the URL query parameters (the key-value pairs after the `?`). // For a URL like /search?term=expressjs
    app.get('/search', (req, res) => {
    const searchTerm = req.query.term;
    res.send(`You searched for: ${searchTerm}`);
    });
  • `req.body`: Contains data submitted in the request body, typically from a form POST or an API call. Important: You must use middleware like `express.json()` or `express.urlencoded()` for `req.body` to be populated. app.post('/api/users', (req, res) => {
    const userName = req.body.name;
    res.send(`User ${userName} created!`);
    });
  • `req.headers`: An object containing the HTTP headers from the request. app.get('/headers', (req, res) => {
    const userAgent = req.headers['user-agent'];
    res.send(`Your user agent is: ${userAgent}`);
    });

Crafting the Perfect Response (`res`)

The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request. You have full control over what you send back to the client.

Sending JSON, HTML, and Files

  • `res.json()`: The most common method for APIs. It sends a JSON response and automatically sets the `Content-Type` header to `application/json`. res.json({ success: true, data: { id: 1, name: 'John Doe' } });
  • `res.send()`: A versatile method that can send strings, HTML, buffer objects, or even JSON. Express will figure out the `Content-Type` for you. res.send('<h1>Hello from Express!</h1>');
  • `res.sendFile()`: Used to send a file to the client. This is great for serving a single HTML page. Note that you must provide an absolute path to the file. const path = require('path');
    res.sendFile(path.join(__dirname, 'views', 'index.html'));

Serving Static Files with `express.static`

Your web application will need to serve static assets like CSS stylesheets, JavaScript files, and images. Manually creating routes for each of these would be a nightmare. Thankfully, Express provides a built-in middleware for this: `express.static`.

You simply create a folder (commonly named `public`) and tell Express to serve any files from that folder. If a request matches a file in your static directory, Express will serve it automatically.

// In your main app file (e.g., index.js)
app.use(express.static('public'));

// Now, a file at 'public/css/style.css' can be accessed
// from the URL: http://localhost:3000/css/style.css

Handling Form and File Uploads with Multer

Handling `multipart/form-data`, which is primarily used for uploading files, is not natively supported by Express. For this, the most popular solution is a middleware called Multer. It makes the process incredibly simple.

Step 1: Install Multer

npm install multer

Step 2: Configure Multer in your route file

You can configure where to store the files and what to name them.

const express = require('express');
const multer = require('multer');
const router = express.Router();

// Configure storage for uploaded files
const upload = multer({ dest: 'uploads/' });

// Create a route to handle a single file upload
router.post('/upload-profile-pic', upload.single('profile_pic'), (req, res) => {
console.log(req.file); // Information about the uploaded file
console.log(req.body); // Any text fields from the form
res.send('Profile picture uploaded successfully!');
});

module.exports = router;

In this example, `upload.single(‘profile_pic’)` is the middleware. It tells Multer to expect a single file from a form field named `profile_pic`. The uploaded file’s details will then be available on the `req.file` object.

Read Me: ExpressJS: Powerful Guide to Middleware and Routing 2025

Read Me: What is ExpressJS? A Beginner’s Guide to Get Started

Conclusion

Mastering the `req` and `res` objects is fundamental to becoming a proficient Express developer. You now have the tools to parse any incoming request, send back a variety of responses, serve static content, and even handle file uploads. These skills form the backbone of virtually every application you’ll build with Express.

Next, we will explore [how to connect to a database like MongoDB]to make our applications dynamic and persistent.

Frequently Asked Questions (FAQ)

Why is `req.body` undefined even though I’m sending data?

This is almost always because you forgot to include the necessary body-parsing middleware. Make sure you have `app.use(express.json())` for JSON data or `app.use(express.urlencoded({ extended: true }))` for form data at the top of your application file.

What is the difference between `res.send()` and `res.json()`?

While `res.send()` can send JSON, `res.json()` is more explicit. It guarantees the response will be JSON and sets the correct HTTP headers. It’s the recommended method for building APIs.

Can I use `express.static` for more than one directory?

Yes, you can. Simply call `app.use(express.static(‘directory_name’))` for each directory you want to serve. Express will look for files in the order you define the middleware. You can find more details in the official Express documentation on static files.

Leave a Comment