我正在尝试将参数从一个中间件传递到下一个中间件。第一个中间件只是在 req.cookieKey 中存储一个密钥。第二个中间件使用 express 的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) =>
从第二个中间件中删除额外的功能层,它会起作用。
我希望我可以使用我之前设置的 req.cookieKey,然后只返回 cookieSession 函数,但这似乎不起作用。我进行了测试,以确保在设置 cookie 中间件时可以获得 req.cookieKey,但由于某种原因,我无法让 cookieSession 正常工作。有人有什么建议吗?我已经包含了工作版本而没有在此处传递参数:https ://codesandbox.io/s/l2lw7499q9