嗯...您似乎对 cookie 会话的使用有点困惑。
您的 /setcookie 路径未设置任何 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() 调用,每次有人请求@ 987654326@。如果您只想在特定请求中添加cookieSession中间件,您需要执行以下操作:
yourParser = express.cookieSession({ key: "test", secret: "test" });
app.get('/', yourParser, ...);
app.get('/setcookie', yourParser, ...);
解决方案
这是实际的固定来源:
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 对象上设置任何内容。 :)