使用jQuery POST时未保存NodeJS Express会话变量

时间:2014-08-12 20:52:13

标签: jquery node.js express

好的,所以这个问题已经被问了很多次并且用不同的方式,但是,到目前为止,所提出的解决方案都没有对我有用。我有一个非常简单的登录页面,它将用户名和密码传递给我的服务器,服务器对用户进行身份验证并将用户对象保存在会话中:

App.js:

var express = require('express')
              , SessionMongooseStore = require("session-mongoose")(express)
              , SessionStore = new SessionMongooseStore({
                               url: "mongodb://localhost/MySessions",
                               interval: 1200000 
                });

var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());

app.use(express.session({
        store: SessionStore,
        cookie: {maxAge: 36000000},
        secret: 'MySecret'
    }));

app.use(function(req, res, next) {
   res.header('Access-Control-Allow-Credentials', true);
   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
   res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-  Override, Content-Type, Accept');
   next();
});

路线:

app.post('/login',Session.LogIn);

Session.LogIn定义:

exports.LogIn = function(req,res){
    if(req.body){
       var user_name = req.body.email_address;
       var pwd = req.body.password;
       Store.getUser(user_name,pwd,function(err,user){
          if(error) { //do something } 
          else{
            //SAVING DATA TO THE SESSION
            req.session.authenticatedUser = user;
            req.session.foo = 'bar';
            req.session.save();
            var successResponse = {};
            successResponse.redirect = '/redirect';
            res.json(successResponse);
          }
       });
    }
}

我的jQuery AJAX POST:

var post = $.ajax({url: '/login', 
                 type: "POST", 
                 data: querystring, 
                 xhrFields: {withCredentials: true}, 
                 success: function(data) {
                    if(data.code!=200){
                        alert('Log in failed');
                    }
                    else if(data.redirect){
                        window.location = data.redirect;
                    }
                    else{
                        alert('Could not understand response from the server');
                    }
            }});

当我发布POST时,我可以看到会话变量' user'和' foo'设置,我可以打印它们,但当我回到任何路线时,变量是未定义的。例如,打电话' /'登录后:

 app.get('/',function(req,res){
    console.log('--------- Looking for authenticated user saved in session: ' +   req.session.authenticatedUser);
    console.log('--------- Foo: ' + req.session.foo);
    res.render('index');
 });

我明白了:

--------- Looking for authenticated user saved in session: undefined
--------- Foo: undefined

我试图使用FF海报插件为FF重做并执行POST,而不是使用jQuery,并且它工作正常,变量保存在会话对象中。每个POST我都会阅读有关使用

的内容
xhrFields: {withCredentials: true}

使用我的jQuery POST并使用:

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

在我的节点js服务器中,我正在做的,你可以从上面的代码中看到,但仍然没有运气。有什么想法吗?

1 个答案:

答案 0 :(得分:7)

默认情况下,httpOnly标记在true的Cookie设置中设置为express.session,从而拒绝访问xhr请求,例如jQuery所执行的操作。您可以在cookie配置中启用它:

app.use(express.session({
  store: SessionStore,
  cookie: {
    maxAge: 36000000,
    httpOnly: false // <- set httpOnly to false
  },
  secret: 'MySecret'
}));

现在,在ajax请求期间,服务器可以访问客户端的cookie。