Express: How To Use the req Object

Express servers receive data from the client-side through the req object in three instances: the req.params, req.query, and req.body objects.

The req.params object captures data based on the parameter specified in the URL. In your index.js file, implement a GET request with a parameter of '/:userid':

// GET

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

The req.params object tells Express to output the result of a user’s id through the parameter '/:userid'. Here, the GET request to with the designated parameter logs into the console an id of "1".

To access a URL query string, apply the req.query object to search, filter, and sort through data. In your index.js file, include a GET request to the route '/search':

// GET

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

Utilizing the req.query object matches data loaded from the client side in a query conditional. In this case, the GET request to the '/search' route informs Express to match keywords in the search query to The result from appending the .keyword property to the req.query object logs into the console, "great-white".

The req.body object allows you to access data in a string or JSON object from the client side. You generally use the req.body object to receive data through POST and PUT requests in the Express server.

In your index.js file, set a POST request to the route '/login':

//      {
//        "email": "[email protected]",
//        "password": "helloworld"
//      }'/login', (req, res) => {
  console.log( // "[email protected]"
  console.log(req.body.password) // "helloworld"

When a user inputs their email and password on the client side, the req.body object stores that information and sends it to your Express server. Logging the req.body object into the console results in the user’s email and password.

Now that you’ve examined ways to implement the req object, let’s look at other approaches to integrate into your Express server.

Leave a Reply

Your email address will not be published. Required fields are marked *