gpt4 book ai didi

javascript - express.js 路由解释

转载 作者:IT老高 更新时间:2023-10-28 23:26:44 25 4
gpt4 key购买 nike

我在看 源代码,了解它如何将命名路由参数映射到 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);
});

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

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

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

可选 符号之后

星号      * 符号                                                                                                                                                                                                                                                                                          

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


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

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

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

提到的正则表达式是,

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

那么有什么意义呢?


我问这个,因为:

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

最佳答案

用于匹配文件扩展名等。

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

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

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

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

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

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

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

关于javascript - express.js 路由解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com