NodeJS 正在检查url是否包含数字(以express格式)

wz3gfoph  于 2023-01-12  发布在  Node.js
关注(0)|答案(5)|浏览(121)

我在nodejs和express js框架中做一个中间件函数,我想检查url中是否包含数字,就像这样
/发票/21或/发票/45
所以我尝试着做这样的事情

if (req.path.startsWith('/invoices/[^0-9]') {
    next();
  }

但是我得到了错误,我仍然不能这样做,有没有人给予点提示。

nzk0hqpo

nzk0hqpo1#

最快的方法是使用RegExp进行检查

if(RegExp(/^\/invoices\/[0-9]/).test(req.path)){
    // do something
}
vawmfj5a

vawmfj5a2#

不能像这样使用RegExp。startsWith只接受一个字符串。这段代码创建了一个RegExp,并使用match检查该字符串是否与RegExp匹配。

if (req.path.match(new RegExp('/invoices/[^0-9]'))) { // create a regexp and check if it matches
    next();
}
xam8gpfp

xam8gpfp3#

startsWith接收字符串而不是正则表达式。在这种情况下可以使用match

var str = '/invoices/120';
if (str.match(/^\/invoices\/\d+/)) { // return truly value
  next(); // gets executed
} 

var str = '/invoices/abc';
if (str.match(/^\/invoices\/\d+/)) { // return falsy value
  next();
}

您可以在jsfiddle中查看它。

pgvzfuti

pgvzfuti4#

const re = /^\/invoices(\/.*)?\/\d*\//
  if(re.test(req.originalUrl.toLowerCase())) {
    // include a number
  }

//'/invoices/kk/190/foo' will pass
//'/invoices/kk/190k/foo' won't pass

你用的是什么版本的express?我只能通过req.originalUrl访问路径,没有req.path。

tyky79it

tyky79it5#

简化Naman的回答;
如果您正在检查中间件中符合条件的每个URL,您可以这样测试:

if (/^\/invoices\/(\d)+/.test(req.originalUrl)) {
    // Do something when condition is true
}

这假定您现在使用的是最新版本的Express。

相关问题