Express JS Router Middleware Abstraction

I developed the API using Node.js + Express JS and I use token based authentication.

I used two different routers in this api, userRoute (/ USER) and postRoute (/ POST). PostRoute can be used in the authentication process, but userRoute needs a token.

To decide that I am using router middleware for userRoute, but this 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 server checks the token and does not let me in. I know that if I change the order of work of app.use, it works, but I don’t understand why it works this way if I use the "middleware of the router".

Does anyone know?

+4
1

, - , . : node_modules/express/lib/router/index.js. , Router(),

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

:

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

, . , use . use, proto.use

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

, , , .

+1

Source: https://habr.com/ru/post/1658927/


All Articles