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

PropertyDescription
req.paramsAn object containing properties mapped to the named route parameters
req.queryAn object containing a property for each query string parameter in the route
req.bodyContains key-value pairs of data submitted in the request body
req.protocolContains the request protocol string (http or https)
req.hostnameContains the hostname derived from the Host HTTP header
req.pathContains the path part of the request URL
req.originalUrlContains the entire request URL
req.subdomainsAn array of subdomains in the domain name of the request
req.headerAn HTTP header that can be used in an HTTP response
req.cookiesAn object containing cookies sent by the request
req.ipContains 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);
});