WikiCode
WikiCode

Reputation: 55

Express JS Router Middleware Abstraction

I have developed an API using Node.js + Express JS and i use token-based authentication.

I used two differents routers in this api, userRoute (/USER) and postRoute (/POST). The postRoute can be used within authentication but userRoute needs the token.

To solve that i use a router middleware for userRoute but it interferes with portRoute

This is the code:

...

var postRoute = express.Router();
var userRoute = express.Router();


// Route middleware to verify a token
userRoute.use(function(req, res, next) {
    security.checkToken(req,res, next);
});


userRoute.route('/users') 
    .get(userCtrl.findAllUsers)
    .post(userCtrl.addUser);


postRoute.route('/posts') 
    .get(userCtrl.findAllPosts)
    .post(userCtrl.addPost);


app.use(userRoute);
app.use(postRoute);

...

If i try to access '/posts' the servers checks the token and does not let me in. I know if i change the order of app.use it works, but i dont understand why works in this way if i am using "Router Middleware".

Someone knows?

Upvotes: 4

Views: 512

Answers (1)

Stavros Zavrakas
Stavros Zavrakas

Reputation: 3063

This happens because if the express router implementation, you will be able to understand it quite easily if you have a look at it. Here is the path: node_modules/express/lib/router/index.js. Every time that you call the Router(), like in your case

var postRoute = express.Router();
var userRoute = express.Router();

this function will be invoked:

var proto = module.exports = function(options) { ... }

and it is true that there is a different router instance that is being returned every time. The difference is in the way that the use is registering the middlewares. As you see the use it is registered against the proto.use

proto.use = function use(fn) { ... }

this means that the middleware that you register there they will be registered for every instance of the router that you define.

Upvotes: 1

Related Questions