cookie-session 不保存会话修改
cookie-session doesn't save session modification
我想记住某人访问的最后一页 (like here)
我试着用 cookie-session 来做,但它并没有像我想的那样工作。
我看到 and I tried this example 延长会话但没有成功。
这里是代码:
var session = require('cookie-session');
var express = require('express');
var app = express();
app.use( session({ secret: 'secret' }) );
app.get('/a', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "a";
res.end("Page A");
});
app.get('/b', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "b";
res.end("Page B");
});
app.get('/c', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "c";
res.end("Page C");
});
app.listen(8080);
您确定您的日志中没有出现 "cannot write to headers after they have been sent" 行的错误吗?您可以尝试将 session 的分配移动到 res.write 调用之前吗?来自您的第一个 link,在评论中...
“我一直收到错误消息,提示 headers 在发送后无法设置。
我修改了代码,以便在发送任何 body 之前设置 lastPage,例如:
var responseText;
if(req.session.lastPage)
responseText = 'Last page was: ' + req.session.lastPage + '. ';
else
responseText = 'You\'re Awesome';
req.session.lastPage = '/awesome';
res.send(responseText);
我想记住某人访问的最后一页 (like here)
我试着用 cookie-session 来做,但它并没有像我想的那样工作。
我看到
这里是代码:
var session = require('cookie-session');
var express = require('express');
var app = express();
app.use( session({ secret: 'secret' }) );
app.get('/a', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "a";
res.end("Page A");
});
app.get('/b', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "b";
res.end("Page B");
});
app.get('/c', function (req, res) {
if(req.session.last) {
res.write("the last page was " + req.session.last + ". ");
}
req.session.last = "c";
res.end("Page C");
});
app.listen(8080);
您确定您的日志中没有出现 "cannot write to headers after they have been sent" 行的错误吗?您可以尝试将 session 的分配移动到 res.write 调用之前吗?来自您的第一个 link,在评论中...
“我一直收到错误消息,提示 headers 在发送后无法设置。 我修改了代码,以便在发送任何 body 之前设置 lastPage,例如:
var responseText;
if(req.session.lastPage)
responseText = 'Last page was: ' + req.session.lastPage + '. ';
else
responseText = 'You\'re Awesome';
req.session.lastPage = '/awesome';
res.send(responseText);