Express Request Parameters
When building web applications with Express.js, one of the most fundamental skills is knowing how to access and work with data sent from clients to your server. Express provides several ways to access request parameters, each serving different use cases.
Introduction
In web development, clients (browsers, mobile apps, etc.) send data to servers in various ways. Express makes it easy to access this data through different types of request parameters:
- Route Parameters - Parts of the URL path (e.g.,
/users/:id
) - Query Parameters - Data sent after the
?
in a URL (e.g.,/search?q=express
) - Request Body - Data sent in the body of HTTP requests (often in POST, PUT requests)
Understanding how to work with these parameters is crucial for building interactive and dynamic web applications.
Route Parameters
Route parameters are named URL segments used to capture values at specific positions in the URL. They're particularly useful when designing RESTful APIs.
How to Define Route Parameters
Route parameters are defined in your Express route paths with a colon (:
) prefix:
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`Looking at user profile: ${userId}`);
});
Accessing Route Parameters
You access route parameters through the req.params
object:
app.get('/books/:category/:bookId', (req, res) => {
// Access multiple parameters
const category = req.params.category;
const bookId = req.params.bookId;
res.send(`Showing book ${bookId} from category ${category}`);
});
Example: Dynamic Profile Pages
const express = require('express');
const app = express();
// Sample user data (in a real app, this would likely be in a database)
const users = {
'1': { name: 'Alice', role: 'Developer' },
'2': { name: 'Bob', role: 'Designer' },
'3': { name: 'Charlie', role: 'Manager' }
};
app.get('/profile/:userId', (req, res) => {
const userId = req.params.userId;
// Check if user exists
if (users[userId]) {
res.send(`
<h1>Profile for ${users[userId].name}</h1>
<p>Role: ${users[userId].role}</p>
<p>User ID: ${userId}</p>
`);
} else {
res.status(404).send('User not found');
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
If you visit /profile/1
, you'll see Alice's profile information. Visit /profile/2
, and you'll see Bob's profile information.
Query Parameters
Query parameters are key-value pairs that appear after the ?
in a URL. They're commonly used for filtering, sorting, or pagination.
Accessing Query Parameters
Query parameters are accessible through the req.query
object:
app.get('/search', (req, res) => {
const query = req.query.q;
const page = req.query.page || 1; // Default to page 1 if not specified
res.send(`Searching for "${query}" on page ${page}`);
});
For a request to /search?q=javascript&page=2
, the above handler would respond with: "Searching for "javascript" on page 2"
Example: Product Filtering
const express = require('express');
const app = express();
// Sample product data
const products = [
{ id: 1, name: "Laptop", category: "electronics", price: 999 },
{ id: 2, name: "Headphones", category: "electronics", price: 99 },
{ id: 3, name: "T-shirt", category: "clothing", price: 19 },
{ id: 4, name: "Jeans", category: "clothing", price: 49 },
{ id: 5, name: "Coffee maker", category: "kitchen", price: 149 },
];
app.get('/products', (req, res) => {
let filteredProducts = [...products];
// Filter by category if provided
if (req.query.category) {
filteredProducts = filteredProducts.filter(
product => product.category === req.query.category
);
}
// Filter by maximum price if provided
if (req.query.maxPrice) {
const maxPrice = parseInt(req.query.maxPrice);
filteredProducts = filteredProducts.filter(
product => product.price <= maxPrice
);
}
res.json({
count: filteredProducts.length,
products: filteredProducts
});
});
app.listen(3000, () => console.log('Server running on port 3000'));
Now you can make requests like:
/products
- Returns all products/products?category=electronics
- Returns only electronic products/products?maxPrice=100
- Returns products costing $100 or less/products?category=clothing&maxPrice=20
- Returns clothing items costing $20 or less
Request Body Parameters
Request body parameters are used to send data in the body of an HTTP request, particularly in POST, PUT, and PATCH requests. This is the preferred method for sending larger amounts of data or sensitive information.
Setting Up Body Parsing
Before you can access the request body, you need to set up appropriate middleware:
const express = require('express');
const app = express();
// For parsing application/json content
app.use(express.json());
// For parsing application/x-www-form-urlencoded content
app.use(express.urlencoded({ extended: true }));
Accessing the Request Body
Once the middleware is set up, you can access the body data through req.body
:
app.post('/api/users', (req, res) => {
const { username, email, password } = req.body;
// In a real app, you'd validate and save this data
console.log(`New user: ${username}, Email: ${email}`);
res.status(201).json({
message: 'User created successfully',
userId: 'new-user-id' // In a real app, this would be generated
});
});
Example: Contact Form Submission
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve an HTML form
app.get('/contact', (req, res) => {
res.send(`
<h1>Contact Us</h1>
<form method="POST" action="/contact">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<button type="submit">Send Message</button>
</form>
`);
});
app.post('/contact', (req, res) => {
const { name, email, message } = req.body;
// In a real app, you'd save this to a database or send an email
console.log('Contact form submission:');
console.log('Name:', name);
console.log('Email:', email);
console.log('Message:', message);
res.send(`
<h1>Thank you, ${name}!</h1>
<p>We've received your message and will contact you at ${email} soon.</p>
<a href="/contact">Back to Contact Form</a>
`);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Handling All Types of Parameters Together
Often, you'll need to combine different types of parameters in a single route:
app.post('/api/users/:userId/posts', (req, res) => {
const userId = req.params.userId; // Route parameter
const format = req.query.format || 'json'; // Query parameter
const { title, content } = req.body; // Request body parameters
console.log(`User ${userId} is creating a post in ${format} format`);
console.log(`Title: ${title}`);
console.log(`Content: ${content}`);
res.status(201).json({
message: 'Post created successfully',
postId: 'new-post-id'
});
});
Parameter Validation
When working with parameters, it's important to validate them to ensure they meet your expectations:
app.get('/api/products/:id', (req, res) => {
const productId = parseInt(req.params.id);
// Validate that productId is a number
if (isNaN(productId)) {
return res.status(400).json({ error: 'Product ID must be a number' });
}
// Continue with valid parameter
// ...
});
For more complex validations, consider using libraries like express-validator
:
const { body, validationResult } = require('express-validator');
app.post('/api/users',
// Validation middleware
body('username').isLength({ min: 3 }).withMessage('Username must be at least 3 characters'),
body('email').isEmail().withMessage('Must provide a valid email'),
body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'),
(req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process valid data
const { username, email, password } = req.body;
// ...
}
);
Summary
Express provides several ways to access request parameters:
- Route Parameters (
req.params
): Access dynamic segments in the URL path - Query Parameters (
req.query
): Access data after the?
in the URL - Request Body (
req.body
): Access data in the request body (requires middleware)
Understanding these different parameter types allows you to build flexible and powerful APIs and web applications. The appropriate type to use depends on your specific use case:
- Use route parameters for identifying resources
- Use query parameters for filtering, sorting, or pagination
- Use request body for sending larger amounts of data or sensitive information
Always remember to validate parameters to ensure data integrity and security in your application.
Additional Resources and Exercises
Resources
- Express.js Official Documentation on Request Parameters
- Express API Reference for Request Objects
- Express-validator Documentation
Exercises
-
Basic Route Parameters: Create a route
/greet/:name
that returns a personalized greeting based on the name parameter. -
Combining Parameter Types: Build an API endpoint for a blog that allows filtering posts by author (route parameter) and by date range (query parameters).
-
Form Processing: Create a registration form that collects user information (name, email, password) and processes it when submitted.
-
Parameter Validation: Extend the previous exercise by adding validation to ensure that the email has a valid format and the password meets security requirements.
-
RESTful API: Build a small RESTful API for a todo list application that uses all three types of parameters. Allow creating, reading, updating, and deleting todos.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)