Pass data between epress router and middleware

1771 views javascript
1

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 (e.g. not on login/signup routers).

So, I'd like to specify in the router declaration that a route should require a valid token. E.g. 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

answered question

1 Answer

11

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'}));

posted this

Have an answer?

JD

Please login first before posting an answer.