How to use Request Object in Express Nodejs
When a client accesses a route, it sends an HTTP request to your Express app. The request object, abbreviated as req, represents that request. It contains the URL, parameters, query strings, body, headers, and cookies.
Common request properties
| Property | Description |
|---|---|
| req.params | An object containing properties mapped to the named route parameters |
| req.query | An object containing a property for each query string parameter in the route |
| req.body | Contains key-value pairs of data submitted in the request body |
| req.protocol | Contains the request protocol string (http or https) |
| req.hostname | Contains the hostname derived from the Host HTTP header |
| req.path | Contains the path part of the request URL |
| req.originalUrl | Contains the entire request URL |
| req.subdomains | An array of subdomains in the domain name of the request |
| req.header | An HTTP header that can be used in an HTTP response |
| req.cookies | An object containing cookies sent by the request |
| req.ip | Contains the remote IP address of the request |
Accessing user-submitted data
req.params: named URL segments defined with : in your route path.
// GET https://example.com/user/123
app.get('/user/:id', (req, res) => {
console.log(req.params.id); // "123"
});
req.query: values from the query string (the part after ?).
// GET https://example.com/user?userID=123&action=submit
app.get('/user/', (req, res) => {
console.log(req.query.userID); // "123"
console.log(req.query.action); // "submit"
});
req.body: data sent in the request body (POST, PUT). Requires express.json() middleware to be set up before your routes:
app.use(express.json()); // must be before your routes
// POST https://example.com/login body: {username: "anna", password: "1234"}
app.post('/login/', (req, res) => {
console.log(req.body.username); // "anna"
console.log(req.body.password); // "1234"
});
Accessing URL values
// https://learn.devhandbook.com/search?keyword=express
app.get('/search', (req, res) => {
console.log(req.protocol); // "https"
console.log(req.hostname); // "devhandbook.com"
console.log(req.path); // "/search"
console.log(req.originalUrl); // "/search?keyword=express"
console.log(req.subdomains); // ["learn"]
});
Accessing header values
app.post('/login', (req, res) => {
console.log(req.header('Content-Type'));
console.log(req.header('Content-Length'));
console.log(req.header('user-agent'));
console.log(req.header('Authorization'));
});
Accessing cookies
When using the cookie-parser middleware, cookies are available on req.cookies. If the request contains no cookies, it defaults to {}.
app.post('/login', (req, res) => {
console.log(req.cookies.isShowPopup);
console.log(req.cookies.sessionID);
});
What to read next
- Response Object : send responses back to the client
- Middleware
: set up
express.json()and other middleware