NodeJS express-session req.session未定义

时间:2016-05-10 12:13:29

标签: node.js session express cookies login

我正在开发一个简单的登录系统,但似乎没有保存会话

我已经制作了一个简单的测试代码,谁能告诉我它有什么问题? 我正在运行登录,之后我运行了is_logged但是我从未登录过,并且两个会话都是未定义的

var port = process.env.PORT || 8080;
var express = require('express');
var app = express();


var cookieParser = require('cookie-parser');
var session = require('express-session');



app.use(cookieParser());
app.use(session({
    secret: "fd34s@!@dfa453f3DF#$D&W", 
    resave: false, 
    saveUninitialized: true, 
    cookie: { secure: true }
}));



 app.post('/test_login', function(req, res){

    req.session.users_schema = 1;
    req.session.user_doc = 2;

    res.json({"first": req.session.users_schema, "second": req.session.user_doc});
});
 app.post('/test_is_loggin', function(req, res){

    if( !req.session.users_schema || !req.session.user_doc ) { 

        console.log("no");
        res.json({"first": 1, "second": 1});
    }
    else {

        console.log("no2");
        res.json({"first": req.session.users_schema, "second": req.session.user_doc});
    }

 });


app.listen(port);
console.log('Listening on port ' + port);

3 个答案:

答案 0 :(得分:6)

这是因为选项cookie.secure = true

引用

  

请注意,secure:true是推荐选项。但是,它   需要启用https的网站,即HTTPS是安全所必需的   饼干。

请参阅https://github.com/expressjs/session#cookie-options

您必须将其设置为false,以允许非https主机上的会话Cookie,或使用https主机。

测试代码

var port = process.env.PORT || 8080;
var express = require('express');
var app = express();


var cookieParser = require('cookie-parser');
var session = require('express-session');



app.use(cookieParser());
app.use(session({
    secret: "fd34s@!@dfa453f3DF#$D&W",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: !true }
}));



 app.get('/test_login', function(req, res){

    req.session.users_schema = 1;
    req.session.user_doc = 2;

    res.json({"first": req.session.users_schema, "second": req.session.user_doc});
});
app.get('/test_is_loggin', function(req, res){

  if( !req.session.users_schema || !req.session.user_doc ) {

      console.log("no");
      res.json({"first": 1, "second": 1});
  }
  else {

      console.log("OK");
      res.json({"first": req.session.users_schema, "second": req.session.user_doc});
  }

});


app.listen(port);
console.log('Listening on port ' + port);

输出

[mh-cbon@pc15 test] $ node express-session.js 
Listening on port 8080
OK

答案 1 :(得分:0)

我不确定但它可能与我发送数据的方式有关?

<script>

var date = new Date("05/05/2016");


$.ajax({

    type : "POST",
    url : '//localhost:8080/test_login',  
    data : {

    },
    success : function(data) {

        console.log(data);
    },
    error : function(req, errortype) {
        console.log("ERROR");
    }

});

</script>

==========================================

解决!!!

它与我发送数据的方式有关,我将其更改为以下内容:

客户:

$.ajax({

    type : "POST",
    xhrFields: {withCredentials: true},  // ADDED THIS LINE
    url : '//localhost:8080/test_login',
    data : {

    },
    success : function(data) {

        console.log(data);
    },
    error : function(req, errortype) {
        console.log("ERROR");
    }

});

SERVER:

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-Origin", "http://localhost");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

非常感谢@ mh-cbon

答案 2 :(得分:0)

所有有关更改会话配置顺序和路由配置的信息

Server.js

文件

之前:错误

require("./startup/cors")(app);
require("./startup/passport/passport-setup")();
require("./startup/logging")();
require("./startup/validation")();
//require("./startup/db")();
require("./startup/prod")(app);
require("./routes/index")(app);

app.use(
  session({
    secret: 'keyboard cat',//process.env.SESSION_KEY,// Used to compute a hash
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection }),// Store session on DB
  })
);

之后:正确

app.use(
  session({
    secret: 'keyboard cat',//process.env.SESSION_KEY,// Used to compute a hash
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection }),// Store session on DB
  })
);

require("./startup/cors")(app);
require("./startup/passport/passport-setup")();
require("./startup/logging")();
require("./startup/validation")();
//require("./startup/db")();
require("./startup/prod")(app);
require("./routes/index")(app);