In Express.js, the request (req) and response (res) objects are essential for handling HTTP transactions between a client and a server. Here's what you should know:
Request Object (req)
- Represents the HTTP request made by the client
- Contains details such as:
- URL parameters (
req.params) - Query strings (
req.query) - Headers (
req.headers) - Request body (
req.body)
- URL parameters (
Example:
app.get('/users/:id', (req, res) => {
// Access URL parameter
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
Response Object (res)
- Facilitates sending a response back to the client
- Methods include:
-
res.send()for sending a response body -
res.json()for JSON data -
res.status()to set response status codes -
res.redirect()to redirect clients
-
Example:
app.post('/login', (req, res) => {
const { username, password } = req.body;
if(username === 'admin') {
res.status(200).json({ message: 'Login successful' });
} else {
res.status(401).send('Unauthorized');
}
});
Summary
-
reqlets you read data sent by the client -
resallows you to construct and send an appropriate reply
Mastering these objects is central to building efficient Express.js servers.
Top comments (0)