Node.js Express路由映射:静态路由被动态参数路由拦截如何解决
Express 路由匹配优先级问题解决方案
问题根因
Express 路由遵循从上到下按定义顺序匹配的规则,命中第一个符合规则的路由后就会终止后续匹配。你定义的/customer/:customerId属于动态参数路由,:customerId可以匹配任意不含/的字符串,因此/customer/regions请求发起时会先命中第一个路由,将regions识别为customerId的参数值,无法走到第二个路由。
解决方案
- 方案1:调整路由定义顺序
将固定路径路由放在动态参数路由之前,保证固定路径优先匹配:
// 固定路径路由前置 router.get("/customer/regions", async (request, response) => { console.log("Fetch all customers from a region") }) // 动态参数路由后置 router.get("/customer/:customerId", async (request, response) => { console.log("Fetch customer with a particular customer ID") })
- 方案2:给动态参数添加正则约束
如果不需要调整路由顺序,可以给动态参数增加正则匹配规则,限定参数格式,比如限定customerId只能为数字:
// 限定customerId仅匹配数字,regions字符串不会命中该规则 router.get("/customer/:customerId(\\d+)", async (request, response) => { console.log("Fetch customer with a particular customer ID") }) router.get("/customer/regions", async (request, response) => { console.log("Fetch all customers from a region") })
注意:Express 路由路径建议统一以
/开头,避免路由挂载时出现路径拼接错误。
内容的提问来源于stack exchange,提问作者MDL
相关产品推荐
相关产品推荐

