在if语句中使用带有参数的请求路径

时间:2019-01-18 22:28:10

标签: node.js

我有一些中间件,需要在其中检测以下路径,即/ events /后跟任何id字符串:

A

但是由于if (req.path === "/events/:eventId" && req.method === "GET") { ... } 部分的原因,这不起作用。我该如何工作?

这应该被检测到

:eventId

但是其他任何这样的路径类型都不应该:

/events/123456

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式,例如

function foo (path) {
  if (/^\/events\/[^\/]+$/.test(path)) {
    // matches any string starting with /events/
    // plus at least one character that is not another / before the end
    console.log('matched');
  } else {
    console.log('did not match');
  }
}


foo('/events/123456');
// 'matched'
foo('/events/123456/image');
// 'did not match'
foo('/events/'); // bonus
// 'did not match'
foo('/events/123456/'); // but note this tricky one
// 'did not match'

// if you also want to accept '/events/123456/' you could change it to
const betterRegex = /^\/events\/[^\/]+\/?$/;
console.log(betterRegex.test('/events/123456/'));
// true
console.log(betterRegex.test('/events/123456/images'));
// false

// plus you can capture the ID by adding a capture group with ()
const id =  /^\/events\/([^\/]+)\/?$/.exec('/events/123456')[1]
console.log(id) // '123456'

但是,如果您有很多路线,我建议您使用express.js之类的东西,因为它使处理它们变得更加容易。