使用路径参数定义多个Express.js路由

编程入门 行业动态 更新时间:2024-10-23 17:31:54
本文介绍了使用路径参数定义多个Express.js路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何使Express.js与路径/1.1.1和/ login区分开来?

我使用以下代码: p>

app.get('/:x?。:y?。:z?',function(req,res){ ... app.get('/ login',function(req,res){

解决方案

路由按照添加的顺序执行,所以如果你希望你的登录路由优先,先定义它。 >

否则,如果您想根据路由进行决策,可以从处理程序内调用next()函数,如下所示:

app.get('/:x?。:y?。:z?',function(req,res,next){//< == note 'next'参数如果(!req.params.x&!req.params.y&!req.params.z){ next(); // pass控制到下一个路由处理程序} ... }

从快速指南:对于具有相同路径定义的几条路线也是如此,它们将被简单地执行,直到不调用next()并决定响应。

How can I make Express.js distinguish from the paths "/1.1.1" and "/login" ?

I am using the following code:

app.get('/:x?.:y?.:z?', function(req, res){ ... app.get('/login', function(req, res){

解决方案

Routes are executed in the order they are added. So if you want your login route to take precedence, define it first.

Otherwise, in cases where you want to make decisions based on route, you can call the next() function from inside your handler like this:

app.get('/:x?.:y?.:z?', function(req, res, next){ // <== note the 'next' argument if (!req.params.x && !req.params.y && !req.params.z) { next(); // pass control to the next route handler } ... }

From the Express guide: "The same is true for several routes which have the same path defined, they will simply be executed in order until one does not call next() and decides to respond."

更多推荐

使用路径参数定义多个Express.js路由

本文发布于:2023-10-12 16:51:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485304.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   路由   路径   定义   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!