【问题标题】:Express application level middleware and cookieSession, need to add in parameter from prior middleware表示应用级中间件和cookieSession,需要从之前的中间件中添加参数
【发布时间】:2019-02-11 07:15:28
【问题描述】:

我正在尝试将参数从一个中间件传递到下一个中​​间件。第一个中间件只是在 req.cookieKey 中存储一个密钥。第二个中间件使用 express 的cookie-session。通常我会知道如何执行此操作,但是当我尝试在第二个中间件中返回 cookieSession(

这个中间件先来:

const asyncMiddleware = async (req,res,next) => {
    const data = await SecretKeeper.getCredentialPair('cookie');
    req.cookieKey = data.credential;
    next()
  }

在我呼叫的路线中:

    //get key from SecretKeeper to encrypt cookie that will be set in next middleware
    app.use(asyncMiddleware);

    //set cookie middleware, use key from SecretKeeper to sign and verify cookie
    app.use((req, res, next) => {

        return cookieSession({
            name: 'MySession',
            keys: [req.cookieKey],

            // Cookie Options
            maxAge: .30 * 60 * 60 * 1000 // 30 min
        })
    })

如果我不尝试从 SecretManager(第一个中间件)添加密钥并从第二个中间件中删除额外的功能层 (req, res, next) =>,它会起作用。

我希望我可以使用我之前设置的 req.cookieKey,然后只返回 cookieSession 函数,但这似乎不起作用。我进行了测试,以确保在设置 cookie 中间件时可以获得 req.cookieKey,但由于某种原因,我无法让 cookieSession 正常工作。有人有什么建议吗?我已经包含了工作版本而没有在这里传递参数:https://codesandbox.io/s/l2lw7499q9

【问题讨论】:

    标签: javascript node.js express cookie-session


    【解决方案1】:

    cookieSession(options) 返回function(req, res, next),所以你必须运行它:

    app.use((req, res, next) => {
    
        cookieSession({
            name: 'MySession',
            keys: [req.cookieKey],
    
            // Cookie Options
            maxAge: .30 * 60 * 60 * 1000 // 30 min
        })(req, res, next) //here
    })
    

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2021-09-13
      • 2015-12-08
      相关资源
      最近更新 更多