【问题标题】:Pass data between express router and middleware在快速路由器和中间件之间传递数据
【发布时间】:2019-02-20 20:16:23
【问题描述】:

我正在尝试编写快速中间件来检查授权标头中 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) 参数,所以我真的看不到为每条路线传递起始数据的方法。我确定我错过了一些简单的东西

【问题讨论】:

    标签: javascript node.js express


    【解决方案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) => {});
    

    【讨论】:

    • 除非我遗漏了一些东西,否则您可以在实例化中间件时将数据传递给中间件一次。不是,在实例化路由时按路由?
    • 嗨@jonhobbs,我更新了答案以添加route basis middleware
    • 谢谢,我不完全理解中间件是如何在调用中间的“auth”函数中显式调用的,但你的回答告诉我,可以将多个函数链接在一起路由,所以我可以为每条路由调用一个身份验证函数,而从外观上看根本不使用中间件。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2015-11-16
      相关资源
      最近更新 更多