when using path-to-regexp, how to match all path that not starting with /api/
?
By using native JavaScript RegExp /^(?!\/api\/).*/
will match/x/y/z
. see test result from here
However, it does not work with path-to-regexp. see the test result from there
So what's the correct way to achieve my goal in path-to-regexp?
[Update 1]
More details: The real case is that I'm using angular2 + koajs. And in angular2, browser may issue a client routing url to server. Please see my another question about this.
To address that issue, as suggested by @mxii, I'm trying to use koa-repath to redirect all requests that not started with /api/
to the root url: http://localhost:3000/
excepte it's static assets (js/json/html/png/...) requests.
And koa-repath
use path-to-regexp
to match the path. That's why I asked this question.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
An empty regular expression matches everything.
Definition and UsageThe "g" modifier specifies a global match. A global match finds all matches (compared to only the first).
A regular expression consists of a pattern and optional flags: g , i , m , u , s , y . Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. The method str. match(regexp) looks for matches: all of them if there's g flag, otherwise, only the first one.
See my comment for an explanation about how the express route tester works.
If you just want a simple regex to check that a string doesn't start with api
or /api
, you don't need "path-to-regex" for that, you can simply use this regex:
/^(?!\/?api).+$/
Explanation:
^ => beginning of string
(?!) => negative look-ahead
\/? => 0 or 1 slash
.+ => 1 or more character (any except newline)
$ => end of string
So you get a match if the start of the string is not followed by /api
(optional slash).
See http://regexr.com/3e3a6 for an example.
Edit: If you want it the other way round (only match urls starting with /api
or api
, you can use positive look-ahead:
^(?=\/?api).+$
http://regexr.com/3e3a9
But it's even simpler then:
^\/?api.*$
http://regexr.com/3e3af
I was trying to do the same thing. It seems like the people who answered didn't actually try to understand what you were asking.
I'm not sure if it's possible to do in path-to-regexp. It seems like it doesn't have negative look ahead.
What you can do is change the order that you route the paths. Add your api routing to express / whatever before you add your static stuff.
app.use('/api', require('./api'));
app.get('/*', function (req, res) {
//serve angular app
});
I did it like this and the api route also works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With