My request returns null, but everything seems alright in Express

Issue

I have a router whose method is not called. In the main index.ts I have

app.use("/api/tshirts", tshirts)

Then in tshirts.ts I have

router.get("/", tshirtsController.getTShirts)

router.get("/:productId", 
tshirtsController.getTShirtByProductId)

router.get("/findProductsByIds", 
tshirtsController.getTShirtsByIds)

router.get("/other", (req, res) => {
  console.log("here")
  res.json({msg: "hello"})
})

When I try to hit this route with this URL: http://localhost:5050/api/tshirts/other in Postman, I don’t get the console log in node and hello in the body of the response. I get null in the body and status 200. When I send requests to routes that don’t exist I get status 404. The route is correct, everything seems ok but it doesn’t work. Why?

Solution

Your route using /:productId will trigger for /api/tshirts/other

Try positioning the /:productId route after your /other route in tshirts.ts

Answered By – Thomas Zimmermann

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published