简体   繁体   English

如何在快递服务器中添加动态路由?

[英]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" 我想为我的React应用程序创建一些自定义终结点,使用express作为我的“假服务器”

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. 但显然我无法执行此操作,因为尚未定义productId but is there anyway when I make my axios.get request this can build/inject a route for me. 但是无论如何,当我发出axios.get请求时,它可以为我建立/注入一条路线。 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 . productId将作为req.params的属性在路由处理程序中req.params

More info in the official docs: https://expressjs.com/en/guide/routing.html#route-parameters 官方文档中的更多信息: https : //expressjs.com/en/guide/routing.html#route-parameters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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