How to intercept node.js express request
Asked Answered
G

1

31

In express, I have defined some routes

app.post("/api/v1/client", Client.create);
app.get("/api/v1/client", Client.get);
...

I have defined how to handle requests inside a Client controller. Is there a way that I can do some pre-processing to the requests, before handling them in my controller? I specifically want to check if the API caller is authorized to access the route, using the notion of access levels. Any advice would be appreciated.

Gumbo answered 14/6, 2012 at 18:6 Comment(1)
Think of connect/express as a masseur with many hands, each hand being a middleware that massages your request into the correct response. So what Ryan Olds says is 100% correct. ;)Aimeeaimil
M
69

You can do what you need in a couple of ways.

This will place a middleware that will be used before hitting the router. Make sure the router is added with app.use() after. Middleware order is important.

app.use(function(req, res, next) {
  // Put some preprocessing here.
  next();
});
app.use(app.router);

You can also use a route middleware.

var someFunction = function(req, res, next) {
  // Put the preprocessing here.
  next();
};
app.post("/api/v1/client", someFunction, Client.create);

This will do a preprocessing step for that route.

Note: Make sure your app.use() invokes are before your route definitions. Defining a route automatically adds app.router to the middleware chain, which may put it ahead of the user defined middleware.

Minify answered 14/6, 2012 at 18:13 Comment(6)
@ryan-olds, How Do I check 'Content-Type'? I have to set expiry on JSON only, not in all responce.Owner
This is simple interception concept. Are you familiar with more generic, formed way to do this?Thank youDurtschi
I'm wondering if there is anyway to do this and inspect the body as well. #35165308Trenchant
There is, but a body parser needs to be earlier in the stack/middleware.Minify
for your first solution "app.use(app.router);" is no longer requested (and will cause a deprecated exception). Just remove it, and it's perfectGiles
app.router is depricatedCyaneous

© 2022 - 2024 — McMap. All rights reserved.