gpt4 book ai didi

regex - Node js Express 框架 - 正则表达式不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:31 25 4
gpt4 key购买 nike

我正在尝试在我的 Node 应用程序中将 Reg Ex 与 Express 路由结合使用。我希望路由匹配路径“/”或“/index.html”,但它匹配所有内容:(

这是我的路线。

app.get(/\/(index.html)?/, function(req, res){
res.set('Content-Type', 'text/plain');
res.send('Hello from node!');
});

如何让这个正则表达式发挥作用?

最佳答案

试试这个:

app.get(/^\/(index\.html)?$/, function(req, res){
res.set('Content-Type', 'text/plain');
res.send('Hello from node!');
});

如果没有 $,第一个 / 之后的任何内容仍然可以匹配,而 index.html 只是一个可选的前缀。如果没有 ^,它也会匹配 /something/index.html

关于regex - Node js Express 框架 - 正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16477506/

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