最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass data between express router and middleware - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Sep 17, 2018 at 0:00 etarhan 4,1762 gold badges17 silver badges29 bronze badges asked Sep 16, 2018 at 21:49 jonhobbsjonhobbs 28k38 gold badges118 silver badges179 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

};
发布评论

评论列表(0)

  1. 暂无评论