5

我想在异步请求后更改会话 cookie,但无论我尝试什么,我都会失败。我的要求如下:

$.ajax({
    type: "POST",
    url: "/setStatus",
    data: { userId : _userId, token: _token, tokenSecret : _tokenSecret, service : service, loggedIn : _loggedIn, authorized : _authorized },
    xhrFields: { withCredentials: true },
    crossDomain: true
}).done(function(reply) { alert('finished'); });

在服务器上设置会话变量。

exports.setStatus = function(req, res)
{
    req.session.userId = req.body.userId;
    req.session.token = req.body.token;
    req.session.tokenSecret = req.body.tokenSecret;
    req.session.service = req.body.service;
    req.session.loggedIn = req.body.loggedIn;
    req.session.authorized = req.body.authorized;

    res.header('Access-Control-Allow-Credentials', 'true');
    res.writeHead(200);
};

服务器上的设置如下:

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat', store: new RedisStore({ host: 'localhost', port: 3000, client: dbcon })}));
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

我忘了提到,在简单的请求中,会话 cookie 会按预期更改。有任何想法吗?

4

1 回答 1

7

如果您使用 ajax 进行修改,则应在修改后调用 req.session.save()。

exports.setStatus = function(req, res)
{
    req.session.userId = req.body.userId;
    req.session.token = req.body.token;
    req.session.tokenSecret = req.body.tokenSecret;
    req.session.service = req.body.service;
    req.session.loggedIn = req.body.loggedIn;
    req.session.authorized = req.body.authorized;
    req.session.save(); // This saves the modifications

    res.header('Access-Control-Allow-Credentials', 'true');
    res.writeHead(200);
};
于 2013-05-24T18:23:01.910 回答