Understanding the req Object in Express.js

William Le

Express.js is the most popular server framework because it provides a developer-friendly abstraction of the core http module in Node.js. It’s like using jQuery instead of document.querySelectorAll because it lets you, the developer, be way more productive!

The req object in Express.js allows you to examine every aspect about the request that the client made (whether by browser, by cURL, or mobile browser, etc.). This encompasses lots of things like the URL, user agent string, JSON data, form data… A lot! In this post you’ll learn the basics about the req object in Express.js.

This article isn’t covering req in exhaustive detail, but instead provides an overview of the most popular aspects of req. And you can read this post to learn about the response (res) object.

To view comprehensive docs for the req object, visit the official documentation.

Recommended Node.js video course

User-supplied Data

There are three primary ways for Express.js apps to receive user-supplied data: req.params, req.query, and req.body.

req.params

// GET https://swamp.com/user/50d154c157981ef2

app.get('/:userid', (req, res) => {
  console.log(req.params.userid) // "50d154c157981ef2"
})

req.query

Access the query string in the URL. Many times you’ll see functionality for search, filtering, and sorting use query strings:

// GET https://swamp.com/search?keyword=louisiana-swamps

app.get('/search', (req, res) => {
  console.log(req.query.keyword) // "louisiana-swamps"
})

req.body

Allows you to access the JSON data that was sent in the request. Generally used in POST/PUT requests to send arbitrary-length JSON to the server:

// POST https://swamp.com/login
//
//      {
//        "email": "sam@gmail.com",
//        "password": "chompz4lyfe"
//      }

app.post('/login', (req, res) => {
  console.log(req.body.email) // "sam@gmail.com"
  console.log(req.body.password) // "chompz4lyfe"
})

Examining the URL

The following SVG graphic breaks down the anatomy of an URL:

Anatomy of an URL

// https://mossy.swamp.com/alabama?filter=very-humid

app.get('/alabama', (req, res) => {
  console.log(req.protocol)     // "https"
  console.log(req.hostname)     // "swamp.com"
  console.log(req.path)         // "/alabama"
  console.log(req.originalUrl)  // "/alabama?filter=very-humid"
  console.log(req.subomains)    // "['mossy']"
})

You can easily access various parts of the URL using these built-in properties. Most of these are straight-forward except for req.subdomains which actually gives you an array since you could have multiple subdomains. For example: https://secure.mossy.swamp.com would return ['mossy', 'secure'].

Additional   req   Properties

req.method

Access the HTTP method (GET, POST, PUT, DELETE) with req.method.

app.delete('/', (req, res) => {
  console.log(req.method) // "DELETE"
})

req.header()

Access the headers sent in the request:

app.post('/login', (req, res) => {
  req.header('Content-Type')  // "application/json"
  req.header('user-agent')    // "Mozilla/5.0 (Macintosh Intel Mac OS X 10_8_5) AppleWebKi..."
  req.header('Authorization') // "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
})

The argument for req.header is case-insensitive so you can use req.header('Content-Type') and req.header('content-type') interchangeably.

req.cookies

If you’re using cookie-parser to parse cookies it will store it in req.cookies:

// Cookie sessionDate=2019-05-28T01:49:11.968Z

req.cookies.sessionDate // "2019-05-28T01:49:11.968Z"

Wrapping Up

There you have it! These are the most popular ways that req is used in Express.js. If you’d like to view the official documentation on req please visit the official Express.js docs.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#