Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressJS : middleware based on regex

I have a problem routing using the regex matching feature in expressJS 4.

I want to use app.use() to define what routes are available for the url not starting by /api

routesWebAuth.js

var express = require('express');
var router = express.Router();
var webAuthenticationCtrl = require('controllers/web/auth.js');

router.post('/auth/login',   webAuthenticationCtrl.login);
router.get('/auth/isLogged', webAuthenticationCtrl.isLogged);
router.get('/auth/logout',   webAuthenticationCtrl.logout);

app.js without regex

function routeinfo(req, res) {
  console.log("matched : " + req.path);
  next();
}
//we accept all routes
app.use('/', routeinfo, routesWebIndex);

For the request localhost/auth/login it returns : matched: /auth/login

app.js with regex

function routeinfo(req, res) {
  console.log("matched : " + req.path);
  next();
}
var regex_notApi = /^\/(?!(api))/;
//only the route not starting by /api
app.use(regex_notApi, routeinfo, routesWebIndex);

For the request localhost/auth/login it returns : matched: /

The problem is, in the case where I use the RegEx, the route /auth/login is not matched as the router is provided with the url / instead of /auth/login. how can I fix this ?

like image 618
IggY Avatar asked Jun 24 '26 06:06

IggY


1 Answers

I know it is too late but I think this regex would work:

/^\/((?!api).)*/i
app.use(/^\/((?!api).)*/i, myFunc);

This matches /, /auth, /auth/login, /foo, /foo/bar and ...
And it does not match /api, /api/, /api/foo and ...
Be noticed that it also does not match /apibar/foo which I don't know is your use case or not.

Also you can test express regex routing here: http://forbeslindesay.github.io/express-route-tester/

like image 137
Pouria Moosavi Avatar answered Jun 25 '26 20:06

Pouria Moosavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!