Pasindu Prabhashitha
Pasindu Prabhashitha

Reputation: 390

Passing parameters with express router correctly

import express from "express";
const router = express.Router();

router.route("/:category").get(getProductsByCategories);
router.route("/:id").get(getProductDetails);

export default router;

In this code, I've added two routes with parameters. But this code doesn't work as expected. The first route get products by categories works. But the second one doesn't. Could someone help me to troubleshoot this code, please?

Upvotes: 0

Views: 2082

Answers (2)

Zacquio
Zacquio

Reputation: 347

your route actually same route

use query string

router.route("/").get(getProduct)

and in the product function

const {id,category} = req.query

don't forget to include the keyword in url request

{{url}}/product?id=1 // to get detail
{{url}}/product?category // to get product by category

Upvotes: 1

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

The problem

From the Express documentation here

Route parameters

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.

Route path: /users/:userId/books/:bookId

Request URL: http://localhost:3000/users/34/books/8989

req.params: { "userId": "34", "bookId": "8989" }

With that info, we can say your 2 routes are actually the same. The name of parameters doesn't make them 2 different routes. What it changes is only how the req.params object is populated. As the consequence, all the requests will go to the first route.

Suggestion

You will need to change 1 of 2 routes, for example :

  • To get the product by ID, you can keep it :
router.route("/:id").get(getProductDetails);
  • To get products by category, you can change to :
router.route("/category/:category").get(getProductsByCategories);

Upvotes: 1

Related Questions