express.js - 单行中多个路由的单个路由处理程序 [英] express.js - single routing handler for multiple routes in a single line

查看:40
本文介绍了express.js - 单行中多个路由的单个路由处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

类似于:

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!

有人知道怎么做吗?

推荐答案

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

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

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

@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:

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

    }
);

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"
}, 

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

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.

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

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.

另请参阅@c24w 的回答 下面.

Please also see @c24w's answer below.

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

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.

这篇关于express.js - 单行中多个路由的单个路由处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆