简体   繁体   English

express.js路线说明

[英]express.js routes explanation

I was looking at source code, to find out how it maps named route parameters to req.params properties. 我正在查看源代码,以了解它如何将命名的路由参数映射到req.params属性。

For those who don't know, in express.js you can define routes with named parameters, make them optional, only allow the ones with specific format (and more): 对于那些不知道的人,在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);
});

I realized that the heart of this functionality is a method called pathRegexp() defined in lib/utils.js . 我意识到这个功能的核心是lib / utils.js中定义的一个名为pathRegexp()的方法。 The method definition is as follows: 方法定义如下:

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

The important part is the regex on line 7, /(\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)?/g which groups the matched portions of pathname this way: 重要的部分是第7行的正则表达式,/( /(\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)?/g ( /(\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)?/g/(\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)?/g/(\\/)?(\\.)?:(\\w+)(?:(\\(.*?\\)))?(\\?)?(\\*)?/g以这种方式对路径名的匹配部分进行分组:

slash the / symbol 削减 /符号

format I don't know what is the purpose of this one, explanation needed. 格式 我不知道这个的目的是什么,需要解释。

key the word (ie. \\w+ ) after the : symbol 字(即\\w+后) :符号

capture a regex written in front of the key . 捕获 key前面写的正则表达式。 Should be wrapped in parenthesis (ex. (.\\\\d+) ) 应该用括号括起来(例如(.\\\\d+)

optional the ? 可选 ? symbol after the key key后的符号

star the * symbol 明星 *符号

and the callback handler builds a regex from the groups above. 并且回调处理程序从上面的组构建一个正则表达式。


Now the question is , what is the purpose of format here? 现在的问题是format的目的什么?

My understanding according to the following line: 我的理解如下:

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

and the mentioned regex is, 和前面提到的正则表达式是,

if you put a . 如果你放一个. symbol after the slash group and don't specify a match condition (the regex wrapped in parenthesis after the key ), the generated regex matches the rest of path until it gets to a . slash组之后的符号并且没有指定匹配条件(正则表达式包含在key后的括号中),生成的正则表达式匹配path的其余部分,直到它到达a . or / symbol. /符号。

So what's the point? 那有什么意义呢?


I'm asking this, because: 我问这个,因为:

  1. I want to extract and use this method in my app and want to fully understand how it works before using it. 我想在我的应用程序中提取和使用此方法,并希望在使用它之前完全理解它的工作原理。
  2. I didn't find anything on express.js documentation about it. 我没有在express.js上找到任何关于它的文档。
  3. I'm just curious :) 我只是好奇 :)

It is for matching file extensions and such properly. 它适用于匹配文件扩展名等。

Given the path '/path/:file.:ext' , consider the difference between the expressions: 给定路径'/path/:file.:ext' ,考虑表达式之间的差异:

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

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

In the first case, you end up with params as 在第一种情况下,你最终得到了params

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

but without the format checking, you end up with this: 但没有格式检查,你最终得到这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM