Express.js Request & Response
Every time a client makes a request to your Express server, two objects are created: the **Request** object (`req`) and the **Response** object (`res`). Understanding these objects is fundamental to building any Express application.
The Request Object (req)
The `req` object represents the HTTP request and contains properties for the request query string, parameters, body, HTTP headers, and more.
| Property/Method | Description |
|---|---|
req.params | Route parameters (e.g., `/users/:id` gives `req.params.id`). |
req.query | Query string parameters (e.g., `?sort=asc` gives `req.query.sort`). |
req.body | Request body (requires body-parser middleware). |
req.headers | HTTP headers object. |
req.method | HTTP method (GET, POST, etc.). |
req.url | Request URL. |
req.path | Path part of the URL (without query string). |
req.ip | Client's IP address. |
Request Object Examples
app.get('/users/:id', (req, res) => { console.log('Params:', req.params); <!-- { id: '123' } --> console.log('Query:', req.query); <!-- { sort: 'asc' } for /users/123?sort=asc --> console.log('Method:', req.method); <!-- GET --> console.log('Headers:', req.headers.authorization); <!-- Bearer token... --> res.send('User page');});The Response Object (res)
The `res` object represents the HTTP response that your Express app sends when it gets an HTTP request. It has methods for sending data back to the client.
| Method | Description |
|---|---|
res.send() | Send a response (string, object, array, buffer). |
res.json() | Send a JSON response. |
res.status() | Set HTTP status code. |
res.sendStatus() | Set status and send its string representation. |
res.redirect() | Redirect to another URL. |
res.render() | Render a view template. |
res.set() | Set response headers. |
res.cookie() | Set cookies. |
res.clearCookie() | Clear cookies. |
Response Object Examples
app.get('/text', (req, res) => { res.send('Hello World'); <!-- Sends plain text -->});
app.get('/json', (req, res) => { res.json({ message: 'Hello World', status: 'success' });});
app.get('/not-found', (req, res) => { res.status(404).send('Page not found');});
app.get('/redirect', (req, res) => { res.redirect('/new-page');});
app.get('/download', (req, res) => { res.download('./files/report.pdf');});Chaining Response Methods
Most response methods are chainable:
app.get('/user', (req, res) => { res .status(200) .set('X-Custom-Header', 'Hello') .cookie('visited', 'true') .json({ name: 'John' });});Two Minute Drill
- `req` object contains request information: params, query, body, headers, method, etc.
- `res` object sends responses: `res.send()`, `res.json()`, `res.status()`, etc.
- Use `req.params` for route parameters, `req.query` for query strings.
- Always set appropriate status codes (200, 201, 400, 404, 500, etc.).
- Response methods can be chained for cleaner code.
Need more clarification?
Drop us an email at career@quipoinfotech.com
