简体   繁体   中英

Pass data between express router and middleware

I'm trying to write express middleware to check the validity of a JWT in the Authorization header. This seems quite easy but I don't want it to run on all routes (eg not on login/signup routers).

So, I'd like to specify in the router declaration that a route should require a valid token. Eg something like this

const controllers = require('../controllers');

module.exports = (app) => {

    app.post('/auth/signup', controllers.auth.signup.post);
    app.post('/auth/login', controllers.auth.login.post);

    app.get('/teams', controllers.teams.get, {requiresToken:true});

};

Except, .post and .get don't take a third parameter and the controller only takes (req,res,next) parameters so I can't really see a way of passing startic data for each route. I'm sure I'm missing something simple

This is how i created a middleware to pass the data into

module.exports = function(options) {
   return function (req, res, next) {
        //write your code here
        // here you can access options variable
        console.log(options.data)
        next();
   }
}

How you call that middleware is like this

app.use(middleware({'data' : 'Test'}));

To use on route basis

app.post('/userRegistration', middleware({'data' : 'Test'}), (req, res) => {});

You can exclude the auth subroute from this middleware using negative lookup regexp:

const controllers = require('../controllers');

module.exports = (app) => {

    app.use(/\/((?!auth).)*/, yourJwtTokenValidatorMethod); // replace with your jwt token validator middleware

    app.post('/auth/signup', controllers.auth.signup.post);
    app.post('/auth/login', controllers.auth.login.post);

    app.get('/teams', controllers.teams.get, {requiresToken:true});

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM