Introduction

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys. Expressjs official Docs

Let’s say we defined a route(see the previous article ) in our app in the example code:

const express = require('express')
const app = express()

// a route that takes params:
app.get('/users/:userId/books/:bookId', (req, res) => {
  // we can extract parameters from the route from req.params object
  const userId = req.params.userId
  const bookId = req.params.bookId
  // use userId and bookId values to do something useful
})

Maps to something like this:

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

Important Note:

It’s important to sanitize and validate any input coming from the client requests. Requests are user-constructed data and can contain anything. There are libraries that can be used to perform sanitization for every possible kinds of data.

Summary

Route params are useful if we need to pass data to our app within a Request URL. From our app, we may extract these values and look up the item or more data from a Redis store, etc and return meaningful data inside the HTTP Response

Always remember to sanitize and validate any data that comes in from a Request. Requests are user-constructed and may contain anything.

Next we shall dive into: Next, we shall dive into:

  1. Post Requests in detail
  2. Route handlers
  3. Middleware - How middlewares make Express robust.

Follow me on twitter @nkmurgor where I tweet about interesting topics.