Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for express router url to match path starting with /public/

Tags:

Requirement: Need match all the urls starting with /public/ token.

What I have tried: I tried the below regular expression to match all the paths which are starting with /public/

RegEx: /\/public\/.*/

When I use the same in regex101, it able to match the urls those are starting with /public/ token

But when tried the same in Express router tester (http://forbeslindesay.github.io/express-route-tester/?_ga=1.180272292.1056934125.1459765156) Its not working

Can any one help me know the reason why its not working!!

Sample code:

My expectation is that all the URLs stating with /public/ token should go via this route

router.route(/\/public\/.*/)
        .get(function(req, res, result){
            // TODO
        });

Exs:

https://localhost:8082/public/styles/styles.css
https://localhost:8082/public/js/rs.css
https://localhost:8082/public/images/qq.png
like image 599
kalki Avatar asked Apr 04 '16 10:04

kalki


2 Answers

See this note:

Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

Regex can be used with the following Express syntax:

app.get(/\/public\/.*/, function(req, res) { 
   res.send('/\/public\/.*/'); 
});

However, it seems you can use simpler wildcard pattern with route.route:

router.route('/public/*')

Where * matches any 0+ characters.

like image 61
Wiktor Stribiżew Avatar answered Sep 28 '22 02:09

Wiktor Stribiżew


Write-up from my comment:

While you can use Regex to match all URL's matching '/public', you don't need to - you can just use the following for the route:

router.route('/public/*')
like image 44
Ash Avatar answered Sep 28 '22 02:09

Ash