简体   繁体   English

在快速路由器和中间件之间传递数据

[英]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. 我正在尝试编写快速中间件,以检查Authorization标头中JWT的有效性。 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. 除非.post和.get不采用第三个参数,而控制器仅采用(req,res,next)个参数,所以我真的看不到为每条路线传递起始数据的方法。 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: 您可以使用负查找regexp从此中间件排除auth路由:

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

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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