简体   繁体   中英

how to use path-to-regexp to match all paths that's not starting with /api/?

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.

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.

Regex required for the pattern blow [/somestring]+,

for example,

  1. /api - valid
  2. /asdsa - valid
  3. / - invalid
  4. asdsa - invalid
  5. /asd/asd/asd - valid
  6. /as/ - invalid
  7. /aas/a - valid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM