node.js express.js - 单行中多个路由的单个路由处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15350025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:49:32  来源:igfitidea点击:

express.js - single routing handler for multiple routes in a single line

node.jsregexexpressrouting

提问by Aronis Mariano

Is there a way to make this on a single function call?

有没有办法在单个函数调用中做到这一点?

var todo = function (req, res){};

app.get("/", todo);
app.get("/blabla", todo);
app.get("/blablablabla", todo);

Something like:

就像是:

app.get("/", "/blabla", "/blablablabla", todo );

I know this is a syntax mess, but just for giving an idea of what I would like to achieve, an array of the routes would be awesome!

我知道这是一个语法混乱,但只是为了让我知道我想要实现的目标,一组路由会很棒!

Anyone know how to do this?

有人知道怎么做吗?

回答by Kevin Teljeur

I came across this question while looking for the same functionality.

我在寻找相同的功能时遇到了这个问题。

@Jonathan Ong mentioned in a comment above that using arrays for paths is deprecated but it is explicitly described in Express 4, and it works in Express 3.x. Here's an example of something to try:

@Jonathan Ong 在上面的评论中提到,不推荐使用数组作为路径,但它在 Express 4 中有明确描述,并且它在 Express 3.x 中有效。这是一个可以尝试的例子:

app.get(
    ['/test', '/alternative', '/barcus*', '/farcus/:farcus/', '/hoop(|la|lapoo|lul)/poo'],
    function ( request, response ) {

    }
);

From inside the requestobject, with a path of /hooplul/poo?bandle=froo&bandle=pee&bof=blarg:

request对象内部,路径为/hooplul/poo?bandle=froo&bandle=pee&bof=blarg

"route": {
    "keys": [
        {
            "optional": false, 
            "name": "farcus"
        }
    ], 
    "callbacks": [
        null
    ], 
    "params": [
        null, 
        null, 
        "lul"
    ], 
    "regexp": {}, 
    "path": [
        "/test", 
        "/alternative", 
        "/barcus*", 
        "/farcus/:farcus/", 
        "/hoop(|la|lapoo|lul)/poo"
    ], 
    "method": "get"
}, 

Note what happens with params: It is aware of the capture groups and params in all of the possible paths, whether or not they are used in the current request.

注意 params 会发生什么:它知道所有可能路径中的捕获组和参数,无论它们是否在当前请求中使用。

So stacking multiple paths via an array can be done easily, but the side-effects are possibly unpredictable if you're hoping to pick up anything useful from the path that was used by way of params or capture groups. It's probably more useful for redundancy/aliasing, in which case it'll work very well.

因此,通过数组堆叠多个路径可以轻松完成,但如果您希望从通过参数或捕获组使用的路径中获取任何有用的东西,则副作用可能是不可预测的。它可能对冗余/混叠更有用,在这种情况下它会工作得很好。

Edit: Please also see @c24w's answer below.

编辑:另请参阅下面@c24w 的回答。

Edit 2: This is a moderately popular answer. Please keep in mind that ExpressJS, as with most Node.js libraries, is a moveable feast. While the routing above does still work (I'm using it at the moment, a very handy feature), I cannot vouch for the output of the request object (it's certainly different from what I've described). Please test carefully to ensure you get the desired results.

编辑 2:这是一个中等受欢迎的答案。请记住,与大多数 Node.js 库一样,ExpressJS 是一场流动的盛宴。虽然上面的路由仍然有效(我现在正在使用它,这是一个非常方便的功能),但我不能保证请求对象的输出(它肯定与我所描述的不同)。请仔细测试以确保获得所需的结果。

回答by Jonathan Ong

app.get('/:var(bla|blabla)?', todo)

:varsets the req.paramthat you don't use. it's only used in this case to set the regex.

:var设置req.param你不使用的。它仅在这种情况下用于设置正则表达式。

(bla|blabla)sets the regex to match, so it matches the strings blaand blablah.

(bla|blabla)将正则表达式设置为匹配,因此它匹配字符串blablablah

?makes the entire regex optional, so it matches /as well.

?使整个正则表达式可选,因此它也匹配/

回答by alex

You can actually pass in an array of paths, just like you mentioned, and it works great:

您实际上可以传入一系列路径,就像您提到的那样,并且效果很好:

var a = ['/', '/blabla', '/blablablabla'];
app.get(a, todo);

回答by c24w

Just to elaborate on Kevin's answer, this is from the 4.x docs:

只是为了详细说明凯文的回答,这是来自4.x 文档

The path for which the middleware function is invoked; can be any of:

  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.

调用中间件函数的路径;可以是以下任何一种:

  • 表示路径的字符串。
  • 路径模式。
  • 匹配路径的正则表达式模式。
  • 以上任何一项的组合数组。


They have some examples, including:

他们有一些例子,包括:

This will match paths starting with /abcd, /xyza, /lmn, and /pqr:

app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
  next();
});

这将匹配路径开始/abcd/xyza/lmn,和/pqr

app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
  next();
});

回答by Augustin Riedinger

I went for a:

我去了:

['path', 'altPath'].forEach(function(path) {
  app.get(path, function(req, res) { etc. });
});

回答by Roman Mahrer

require the file of your original route and define the new route like this

需要原始路线的文件并像这样定义新路线

var user = require('./users');
router.post('/login', user.post('/login'));