ExpressJs Request and Response Objects
Syntax
const express = require('express')
const app = express()
app.get('/', (req, res) => {
// Request object
const { headers, url, method } = req
const userAgent = headers['user-agent']
// Response object
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World')
})
Example
Let's say we have the following server.js
file:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const { headers, url, method } = req
const userAgent = headers['user-agent']
console.log(`Request received: ${method} ${url}`)
console.log(`User-Agent: ${userAgent}`)
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World')
})
app.listen(3000, () => {
console.log('Server is listening on port 3000')
})
When we run this file, and make a request to http://localhost:3000/
in our browser, we will see the following output in our terminal:
Request received: GET /
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3
And the browser will display "Hello World".
Explanation
The Request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. The Response object represents the HTTP response that an Express app sends when it receives an HTTP request.
In the example above, we are accessing the Request object to get the HTTP headers and user agent, and we are modifying the Response object by setting the status code, content type, and sending a response body.
Use
The Request and Response objects are used in Express.js to handle HTTP requests and responses respectively.
To access the Request object, use the req
parameter in your route handler function.
To modify the Response object, use the methods provided by the res
parameter in your route handler function.
Important Points
- The Request object represents an HTTP request and the Response object represents an HTTP response.
- The Request object has properties for the request query string, parameters, body, HTTP headers, and so on.
- The Response object has methods that allow you to modify the response being sent back to the client, such as setting HTTP headers and response body.
Summary
In summary, the Request and Response objects are crucial components of Express.js. They are used to handle HTTP requests and responses respectively. The Request object provides access to all the properties of an HTTP request, such as its headers and query parameters. The Response object provides methods for setting HTTP headers, sending response bodies, and ending the response.