Req.params vs req.query vs req.body in Express: Key Differences and Usage
req.params holds route parameters from the URL path, req.query contains URL query string parameters, and req.body carries data sent in the request body, usually from POST or PUT requests. Each serves a different purpose for accessing client-sent data in HTTP requests.Quick Comparison
Here is a quick table comparing req.params, req.query, and req.body in Express:
| Feature | req.params | req.query | req.body |
|---|---|---|---|
| Source | URL path segments defined in route | URL query string after ? | HTTP request body content |
| Typical HTTP Methods | GET, POST, PUT, DELETE (in URL) | GET (usually) | POST, PUT, PATCH |
| Data Format | String values from URL | String values from URL | Usually JSON, form data, or text |
| Use Case | Identify resource by ID or name in URL | Filter or sort data via URL | Send complex data like forms or JSON |
| Access Example | /user/:id → req.params.id | /search?term=js → req.query.term | JSON body → req.body object |
Key Differences
req.params contains values extracted from the URL path defined by route parameters. For example, in a route like /user/:id, the id part is a parameter accessible via req.params.id. This is useful for identifying specific resources.
req.query holds key-value pairs from the URL query string, which comes after the ? in a URL. These are typically used for filtering, sorting, or searching, like /products?category=books. The values are always strings.
req.body contains data sent in the request body, usually with POST, PUT, or PATCH requests. This data can be JSON, form data, or other formats and requires middleware like express.json() to parse. It is used for sending complex or large data from the client to the server.
Code Comparison
import express from 'express'; const app = express(); app.get('/user/:id', (req, res) => { res.send(`User ID from req.params: ${req.params.id}`); }); app.listen(3000, () => console.log('Server running on port 3000'));
req.query Equivalent
import express from 'express'; const app = express(); app.get('/search', (req, res) => { res.send(`Search term from req.query: ${req.query.term}`); }); app.listen(3000, () => console.log('Server running on port 3000'));
When to Use Which
Choose req.params when you need to capture specific parts of the URL path, like IDs or names that identify a resource.
Choose req.query when you want to accept optional filters, sorting options, or search terms via the URL query string.
Choose req.body when the client sends data in the request body, such as form submissions or JSON payloads, typically in POST or PUT requests.
Key Takeaways
req.params extracts dynamic segments from the URL path.req.query reads key-value pairs from the URL query string.req.body holds data sent in the request body, often JSON or form data.req.params for resource identification, req.query for filtering, and req.body for sending complex data.express.json() is needed to parse req.body.