【问题标题】:express.js routes explanationexpress.js 路由解释
【发布时间】:2013-03-09 21:27:28
【问题描述】:

我正在查看 源代码,以了解它如何将命名路由参数映射到req.params 属性。

对于那些不知道的人,在 express.js 中你可以定义带有命名参数的路由,使它们成为可选的,只允许具有特定格式(以及更多)的路由:

app.get("/user/:id/:name?/:age(\\d+)", function (req, res) {
    console.log("ID is", req.params.id);
    console.log("Name is", req.params.name || "not specified!");
    console.log("Age is", req.params.age);
});

我意识到这个功能的核心是在lib/utils.js 中定义的一个名为pathRegexp() 的方法。方法定义如下:

function pathRegexp(path, keys, sensitive, strict) {
    if (path instanceof RegExp) return path;
    if (Array.isArray(path)) path = '(' + path.join('|') + ')';
    path = path
        .concat(strict ? '' : '/?')
        .replace(/\/\(/g, '(?:/')
        .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function (_, slash, format, key, capture, optional, star) {
            keys.push({ name: key, optional: !! optional });
            slash = slash || '';
            return ''
                + (optional ? '' : slash)
                + '(?:'
                + (optional ? slash : '')
                + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
                + (optional || '')
                + (star ? '(/*)?' : '');
        })
        .replace(/([\/.])/g, '\\$1')
        .replace(/\*/g, '(.*)');
    return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}

重要的部分是第 7 行的正则表达式,/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g,它以这种方式对路径名的匹配部分进行分组:

斜线     / 符号                                                                                                                                                                                                                                                                                     

格式   我不知道这个的目的是什么,需要解释。

键       这个词(即\w+:符号 kbd>

捕获 写在key 前面的正则表达式。应该用括号括起来(例如(.\\d+)

可选 ? 987654335 @ kbd>

星号       * 符号                                                                                                                                                                                                                                                                                        

回调处理程序从上面的组构建一个正则表达式。


现在的问题是,这里format的目的是什么?

我的理解是根据下面这行:

(format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)'))

提到的正则表达式是,

如果您在slash 组之后放置. 符号并且未指定匹配条件(正则表达式包裹在key 之后的括号中),则生成的正则表达式匹配path 的其余部分,直到它获取./ 符号。

那么有什么意义呢?


我问这个,因为:

  1. 我想在我的应用程序中提取和使用这个方法,并想在使用它之前完全了解它是如何工作的。
  2. 我没有在 express.js 文档中找到任何关于它的内容。
  3. 我只是好奇 :)

【问题讨论】:

    标签: express.js javascript regex node.js express


    【解决方案1】:

    用于匹配文件扩展名等。

    给定路径'/path/:file.:ext',考虑表达式之间的区别:

    // With 'format' checking
    /^\/path\/(?:([^\/]+?))(?:\.([^\/\.]+?))\/?$/
    
    // Without 'format' checking
    /^\/path\/(?:([^\/]+?))(?:([^\/]+?))\/?$/
    

    在第一种情况下,您最终得到的参数为

    {
        file: 'file',
        ext: 'js'
    }
    

    但是如果没有格式检查,你会得到这样的结果:

    {
        file: 'f',
        ext: 'ile.js'
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2018-03-03
      相关资源
      最近更新 更多