我试图将参数从一个中间件传递给下一个。第一个中间件只是在req.cookieKey中存储一个密钥。第二个中间件正在使用express的cookie-session。通常,我会知道该怎么做,但是当我尝试在第二个中间件中返回cookieSession(时,会有些问题。请参见下面的代码,以及位于底部的codeandbox.io上的示例。
该中间件排在第一位:
#include <iostream>
#include "./include/firebase/app.h"
#include "./include/firebase/database.h"
using namespace std;
using namespace firebase;
using namespace database;
int main () {
::firebase::AppOptions appOptions = ::firebase::AppOptions();
appOptions.set_api_key("AIzaSyDocIMJCv9ZfPq8ozvkeSc5PlC-X5gW5_k");
appOptions.set_app_id("smarttrafficmonitoring.firebaseapp.com");
appOptions.set_database_url("https://smarttrafficmonitoring.firebaseio.com");
appOptions.set_project_id("smarttrafficmonitoring");
appOptions.set_storage_bucket("smarttrafficmonitoring.appspot.com");
appOptions.set_messaging_sender_id("220108272524");
::firebase::App* app;
app = ::firebase::App::Create(appOptions);
::firebase::database::Database *database = ::firebase::database::Database::GetInstance(app);
firebase::database::DatabaseReference dbref = database->GetReference("intersections");
dbref.Child("intersection").Child("NSLane").Child("mid").SetValue(11);
cout << "It worked";
return 0;
}
在我的路线中,我打电话给
const asyncMiddleware = async (req,res,next) => {
const data = await SecretKeeper.getCredentialPair('cookie');
req.cookieKey = data.credential;
next()
}
如果我不尝试从SecretManager(第一个中间件)中添加密钥,并且从第二个中间件中删除了额外的功能层 //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
})
})
,则该方法有效。
我希望我可以使用之前设置的req.cookieKey,然后只返回cookieSession函数,但这似乎不起作用。我进行了测试,以确保在设置Cookie中间件时可以获取req.cookieKey,但是由于某种原因,我无法使cookieSession正常工作。有人有什么建议吗?我包含的工作版本未在此处传递参数:https://codesandbox.io/s/l2lw7499q9
答案 0 :(得分:0)
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
})