简体   繁体   中英

How to add dynamic routes in express server?

I want to make some custom endpoints for my react application, using express as my "fake server"

I have a shopping application. for some products/checkouts I want to add coupons. they get "applied" in the frontend/react side, that makes a request to the backend/server. and then it either comes back saying "coupon is valid", and changes the price for me. or says "coupon is not valid"

I want to hit a dynamic endpoint like this:

app.get(`/product/${productId}/coupons`, function(req, res) {})

but obviously I can't do this as productId has not been defined. but is there anyway when I make my axios.get request this can build/inject a route for me. or how can I add "dynamic" routes in express to solve this problem?

What you are looking for are express router params, you can define them this way:

app.get(`/product/:productId/coupons`, function(req, res) {})

And productId will be available inside the route handler as a property of req.params .

More info in the official docs: https://expressjs.com/en/guide/routing.html#route-parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM