2

I'm doing an API in nodejs with express as router.

Now i'm trying to implement an client-id and an apikey to add some security to the API, and the problem that i'm facing is the next:

One of my API call is like this: router.get("roles/get-objects/:mail/:filter*?") So this means, that i can request an object like this: /roles/get-objects/mail@mail.com/customer

Now the tricky part begins... when I needed to stablish a middleware to read an client-id and an apikey to verify that the client is authorized to se the API, so I did this:

In the declaration of the middleware, I use this wildcard: router.all('/*', function (req, res, next) { XXXX})

The thing is, I have tried in the middleware, as a wildcard everything... I want that any API call is filtered thru that middleware, but apparently I can't find the right wildcard for it...

When I use /roles/* as wildcard, if I do a request to /roles it does work, but when I use the complete URL like: /roles/get-objects/mail@mail.com/customer it doesn't go thru my middleware.

So anybody has any idea? i'm starting to loose my mind

Thank you so much to all of you!

EDIT: Now i'm using this middleware declaration: router.use(function (req, res, next) {XXXX})

So when I call: /roles/get-objects/

It's executed, the problem is when I add the email to the route: /roles/get-objects/mail@mail.com

The app goes directly to the route that i have for that, but omits my middleware: router.get("roles/get-objects/:mail",

I don't understand why is this happening, apparently everything should go thru my middleware first, or am I wrong?

Daniel
  • 330
  • 1
  • 3
  • 11

1 Answers1

2

If you want to establish a middleware to check all HTTP request whose URL starting with /roles/, the middleware should be placed before any other specific router definition:

router.use('/roles', function(req, res, next) {...});
...
router.get('/roles/get-objects/:mail', ...);

If the middleware is defined after specific route, when HTTP request comes in, the specific route is targeted and processed, the middleware won't be executed any more:

router.get('/roles/get-objects/:mail', ...);
...
router.use('/roles', function(req, res, next) {...}); // This middleware logic won't execute when request is sent to '/roles/get-objects/some-email', as the request has already been handled and response is already sent to browser.
shaochuancs
  • 15,342
  • 3
  • 54
  • 62
  • that was the issue, i was declaring first the get, and then the middleware! Thank you so much :) – Daniel Jul 04 '17 at 08:53