Parse HTTP Requests: URLs, Query Parameters, Route Parameters, and Bodies
🎯 Introduction
By the end of this article, you will be able to read a URL path, query parameters, route parameters, and a JSON body, and identify where each value comes from.
🛠 Prepare the request parameter example
The application endpoints use Express 5 for route matching and request parsing. We read the resulting values directly. The Express course covers initialization and syntax; here we focus on request parameters.
Create request-server.mjs and initialize the app:
import express from 'express';
const app = express();
Add the following snippets to the same file in order, then start listening at the end.
🧭 URL: Read the request path
Use req.path to identify the requested path. This endpoint returns only the path so you can inspect it:
app.get('/path', (req, res) => {
res.json({ path: req.path });
});
Visiting /path?tab=profile returns {"path":"/path"}. req.path excludes query parameters after the question mark; res.json sends the result to the client as JSON.
🔎 Query: Read filter criteria
Query parameters follow the question mark and are suitable for page numbers or filters. For /users?name=Ming, read the name with req.query.name:
app.get('/users', (req, res) => {
const name = req.query.name;
if (name !== undefined && typeof name !== 'string') {
return res.status(400).json({ error: 'name must be a single string' });
}
res.json({ name: name ?? null });
});
Passing name=Ming returns {"name":"Ming"}; omitting it returns {"name":null}. This example only echoes the filter and does not query a database.
Validate query parameters before using them. Repeated parameters with the same name may produce an array, and numeric-looking query values do not automatically become numbers.
🏷 Params: Read a user ID from the path
In /users/:id, :id represents a variable path segment. Express places it in req.params.id:
app.get('/users/:id', (req, res) => {
res.json({ id: req.params.id });
});
Visiting /users/7 returns {"id":"7"}. The value is a string. If the database requires a numeric ID, validate it before conversion. Route parameters usually identify the target resource; query parameters usually provide additional search criteria.
📥 Body: Read a JSON body
Enable parsing middleware before routes that accept JSON. Middleware is a handler that runs as part of request processing, before or after an endpoint. Here it converts a JSON body into an object:
app.use(express.json({ limit: '16kb' }));
limit caps the body at 16 KiB; larger bodies receive 413. Requests should include Content-Type: application/json. The parsed value is available as req.body. You do not need to collect chunks manually or call JSON.parse again.
Extract and return name
This endpoint requires a string name in the JSON body:
app.post('/users', (req, res) => {
if (!req.is('application/json')) {
return res.status(415).json({ error: 'Send JSON' });
}
if (typeof req.body?.name !== 'string') {
return res.status(400).json({ error: 'name must be a string' });
}
res.json({ name: req.body.name });
});
After submitting {"name":"Ming"}, req.body.name is Ming, and the response is {"name":"Ming"}. This only verifies parameter extraction; it does not save a user. Invalid JSON syntax produces 400 in the parsing middleware before this route runs.
🧪 Start the server and check the results
Listen on a port at the end of the file:
app.listen(3000, '127.0.0.1');
Run node request-server.mjs. Visit /path?tab=profile, /users?name=Ming, and /users/7 in a browser to obtain the JSON described above. To submit a body, use:
curl -i http://127.0.0.1:3000/users -H 'Content-Type: application/json' -d '{"name":"Ming"}'
Expect status 200 and {"name":"Ming"}. All examples use port 3000, so stop other practice servers first.
❓ Questions and Answers
Q1: Why does Express provide body when the built-in req does not?
Express's JSON middleware reads and parses the body, then places the result in req.body. It is not an object automatically supplied by the network request.
Q2: Do GET query parameters also need express.json?
No. Query parameters come from the URL; JSON middleware processes the request body.
Q3: Can I query the database as soon as Params contains an ID?
You must still validate the ID format and verify that the current user may access the corresponding data.
🧪 Practice
Change name in the request to a number and confirm a 400 response. Then send the wrong body media type and confirm 415.
// Write your code or record your results here
