jquery - 使用 jQuery POST 时未保存 NodeJS Express session 变量

标签 jquery node.js express

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

应用程序.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 时,我可以看到设置了 session 变量“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 的 HTTP Poster 附加组件并执行 POST,而不是使用 jQuery 来重现这个,它工作正常,变量保存在 session 对象中。我读过的每篇文章都在谈论使用

xhrFields: {withCredentials: true}

使用我的 jQuery POST 并使用:

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

在我的 Node js 服务器中,正如您从上面的代码中看到的那样,我正在做的事情,但仍然没有成功。有什么想法吗?

最佳答案

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

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

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

关于jquery - 使用 jQuery POST 时未保存 NodeJS Express session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273840/

相关文章:

jQuery - 隐藏元素后的文本

node.js - React.js 是否需要有 node_modules 文件夹才能运行?

javascript - mongodb 不保存来自node.js 的条目

SSR 的 Angular 7 Cookie(通用)

sql-server - 如何处理mssql Node 模块中的SQL注入(inject)

jquery - jquery默认切换效果

javascript - jquery 表单点击时不会将值发布到 php

jQuery 仅在我当前所在的 div 中添加内容

javascript - 在NodeJS中获取post数据

javascript - Paypal 在故障转移中如何工作