Express JS: Request Object — Req

joemakuta

Josué Makuta

Posted on May 30, 2023

Express JS: Request Object — Req

Photo by Clément Hélardot on Unsplash

Express Js, What is it ?

Express JS is a Node.js framework designed to quickly build API’s web applications, cross-platform, mobile apps, and make node js easy. Express js framework makes the server-side (backend) management of applications easy.

Logo expressjs

Now that we know what is Express Js, Below is the overview of this module :

Overview

  1. What is the Request Object in Express JS?
  2. How to use the Request Object Req.
  3. Most used properties of the Request Object

Requirements: Basics of Javascript, NodeJs, and Express Js

Request Object, What is it?

Before diving into the ocean, we must understand the underlying concept of Express Js: Middleware.

In Express Js, Middlewares are functions that are executed after a request is sent to the server and before the server sends a response. They are between the user request and the server response and have access to them therefore they can modify them as shown below :

User request >|< Middleware >|< Server response

Here is an example of middleware :



app.use((error, req, res, next) => {
    console.log(req.url);
})


Enter fullscreen mode Exit fullscreen mode

From this code above, we have a middleware that prints out in the console the URL of the user request, app being the express application. Learn more about writing middleware here.

The req is an object that is passed as an argument to the middleware function, represents the HTTP request and has properties for the request such as query string, parameters, body, HTTP headers, and so on.

In this article, conventionally the object is referred to as reqbut its actual name is determined by the parameters of the callback function in which you’re working.

Properties of the Request Object

The request object has multiple properties and each one has a specific purpose. To check all the properties of the request object, Here is a code that prints it out.



app.use((error, req, res, next) => {
    console.log(req);
})


Enter fullscreen mode Exit fullscreen mode

Now let’s take an overview of some useful properties of the request object :

req.path
Contains the path part of the request URL.



// example.com/users
console.dir(req.path)
// => '/users'


Enter fullscreen mode Exit fullscreen mode

res.body
It holds key-value pairs of the data in the user request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

Here is how it is used, the app is our express app.



// for parsing application/json
app.use(express.json()) 
//for parsing application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true }))
//Here is a post resquest, its middleware prints out the body of the requestThe request  object has multiple properties and each one has a specific purpose. To check all the properties of the request object, Here is a code that prints it out.
app.post((req, res) => {
  console.log(req.body);
})


Enter fullscreen mode Exit fullscreen mode

req.params
This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.



// GET /user/tj
console.dir(req.params.name)
// => 'tj'


Enter fullscreen mode Exit fullscreen mode

req.ip
Contains the remote IP address of the request.



console.dir(req.ip)
// => '127.0.0.1'


Enter fullscreen mode Exit fullscreen mode

req.hostname
Contains the hostname derived from the Host HTTP header.



// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'


Enter fullscreen mode Exit fullscreen mode

req.headers
This object receives the headers from the client, i.e. the data sent by the browser.



console.dir(req.headers);
// => {
  host: 'localhost:4200',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"Linux"',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'sec-fetch-site': 'none',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-user': '?1',
  'sec-fetch-dest': 'document',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
  'if-none-match': 'W/"20-xayHqON6qb0v2OGf3SWBojKNliI"'
}


Enter fullscreen mode Exit fullscreen mode

req.app
This property holds a reference to the instance of the Express application that is using the middleware.

Let’s note that the express request object includes also some methods such as :



req.accepts(types)
req.acceptsCharsets(charset [, ])
req.get(field)
req.is(type)


Enter fullscreen mode Exit fullscreen mode

And so on …

Conclusion

The request object req is generally passed to the middleware to enable the developer to modify or customize the req received to the server. It has multiple properties and each one has a specific purpose. So far we have seen some useful properties of that object but feel free to check all the properties of the request object in the official documentation of express.

Hope you found this article helpful, 👏👏👏.

Thank you for reading !

💖 💪 🙅 🚩
joemakuta
Josué Makuta

Posted on May 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related