嗯...您似乎对 cookie 会话的使用有点困惑。
Your /setcookie
path 不设置任何 cookie/会话值。要使用 cookie 会话,您需要设置一些值req.session
, 例如req.session.message = "Hi there!"
这些值现在存储在 cookie 中。
你不能res.app.use()
仅在一个回调中,请求会话就无法以这种方式在其他任何地方工作。要在另一个请求中读取这些 cookie,请将app.use(express.cookieSession({ key: "test", secret: "test" }));
在应用程序级别。
编辑:实际上,我考虑过您的 res.app.use() 调用,每次有人请求时,它可能会通过向您的应用程序添加越来越多的中间件层(cookieSession)来破坏您的应用程序/导致内存泄漏/setcookie
。如果只想在特定请求中添加cookieSession中间件,则需要执行以下操作:
yourParser = express.cookieSession({ key: "test", secret: "test" });
app.get('/', yourParser, ...);
app.get('/setcookie', yourParser, ...);
Solution
这是实际的固定源:
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.cookieSession({ key: "test", secret: "test" }));
app.get('/setcookie', function(req, res, next){
req.session.message = "Hellau there";
res.end();
});
现在检查这些值,在app.get('/',...)
尝试这个:
app.get('/', function(req, res, next){
console.log(req.session); //Yay, this will be available in all requests!
res.end();
});
调试
要回答如何手动解码 cookie 中存储的内容的问题,请查看connect/lib/middleware/cookieSession.js
:
// cookieParser secret
if (!options.secret && req.secret) {
req.session = req.signedCookies[key] || {};
} else {
// TODO: refactor
var rawCookie = req.cookies[key];
if (rawCookie) {
var unsigned = utils.parseSignedCookie(rawCookie, secret);
if (unsigned) {
var originalHash = crc16(unsigned);
req.session = utils.parseJSONCookie(unsigned) || {};
}
}
}
它需要req.cookies[key]
(基本上你已经在做了(req.cookies.test
)),将其弹出utils.parseSignedCookie
并将其弹出utils.parseJSONCookie
.
我将原始 cookie 字符串放入最后的 utils.js 文件中:
var signed = exports.parseSignedCookie(
's:j:{}.8gxCu7lVJHVs1gYRPFDAodK3+qPihh9G3BcXIIoQBhM'
, 'test');
var parsed = exports.parseJSONCookie(signed);
console.log(parsed);
并运行了它。猜猜我得到了什么:
{}
为什么?因为你从来没有在上面设置过任何东西req.session
目的。 :)