Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 28, 2021 03:20 pm GMT

Route Params in expressjs

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/:bookIdRequest URL: http://localhost:3000/users/34/books/8989req.params: { "userId": "34", "bookId": "8989" }

Important Note:

Its 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.

Thanks for stopping by! Happy new year and may the energy be with you!


Original Link: https://dev.to/naftalimurgor/route-params-in-expressjs-m1c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To