问题
We are using the expressJwt library and I want to be able to exclude the GET
for the following route api/items/:id
but not include any routes that look like api/items/:id/special-action
.
So far, I've only been able to exclude all routes that have the :id
.
Below is how we've achieved excluding GET
routes that have :id
.
this.app.use(expressJwt({ secret: secrets.JWT }).unless({
path: [
...
{ url: /\/api\/items\/(.)/, methods: ['GET'] },
...
]
});
I've tried { url: /\/api\/items\/(.)\//, methods: ['GET'] }
but it then does not match to any routes and so no routes with :id
get excluded.
There's something off in the way I'm using the regex, but I'm having a hard time seeing it. Do I need to change the (.)
to not be a match all? I imagine it might be matching the trailing slashes
回答1:
You may use
/^\/api\/items\/([^\/]*)$/
The [^\/]*
negated character class matches 0 or more chars other than /
and the ^
/ $
anchors make sure the pattern will be tried against the whole string.
See the regex demo.
Details
^
- start of string anchor\/api\/items\/
- matches a literal/api/items/
substring([^\/]*)
- Capturing group 1: any 0+ chars other than/
.$
- end of string anchor. Note that in case you want to make sure the[^\/]*
has no/
after, add a$
end of string anchor at the end.
来源:https://stackoverflow.com/questions/45842836/node-expressjwt-unless-specify-id-route