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

Express应用程序级中间件和cookieSession,需要从现有的中间件参数添加

运维笔记admin8浏览0评论

Express应用程序级中间件和cookieSession,需要从现有的中间件参数添加

Express应用程序级中间件和cookieSession,需要从现有的中间件参数添加

我想从一个中间件到下一个传递参数。第一个中间件只是存储req.cookieKey密钥。第二中间件采用快递的cookie-session。通常我会知道如何做到这一点,但是当我尝试返回cookieSession(第二中间件东西是打破。见下面我的代码和codesandbox.io底部相连的例子。

该中间件至上:

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) =>

我希望我可以用我前面设置,然后就返回cookieSession功能req.cookieKey但似乎并不奏效。我测试,以确保我能得到req.cookieKey当我设置cookie的中间件,但由于某种原因,我不能让cookieSession正常工作。任何人有什么建议?我已经包括了工作版本,而在这里传递参数:

回答如下:

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
})
发布评论

评论列表(0)

  1. 暂无评论