Route Params in expressjs
Naftali Murgor
Posted on December 28, 2021
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:
- Post Requests in detail
- Route handlers
- Middleware - How middlewares make Express robust.
All sample code is host at github
Thanks for stopping by! Happy new year and may the energy be with you!
Posted on December 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
December 14, 2023