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

时间:2018-09-16 21:49:46

标签: javascript node.js express

我正在尝试编写快速中间件,以检查Authorization标头中JWT的有效性。这似乎很容易,但我不希望它在所有路由上运行(例如,不在登录/注册路由器上运行)。

因此,我想在路由器声明中指定路由应要求有效的令牌。例如。像这样

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

};

除了.post和.get都不采用第三个参数,而控制器仅采用(req,res,next)个参数,因此我真的看不到为每条路线传递起始数据的方法。我确定我缺少简单的东西

2 个答案:

答案 0 :(得分:1)

这是我创建中间件以将数据传递到

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

您怎么称这种中间件

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

要按路线使用

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

答案 1 :(得分:1)

您可以使用否定查找正则表达式从此中间件中排除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});

};