NodeJS express-session req.session is undefined

后端 未结 3 1997
独厮守ぢ
独厮守ぢ 2021-01-22 14:42

I am working on a simple login system, but it seems like the session is not saved

i have made a simple code for testing, can anyone tell me what is wrong with it ? i am

3条回答
  •  执笔经年
    2021-01-22 15:01

    It is because of the option cookie.secure = true

    quote

    Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies.

    see https://github.com/expressjs/session#cookie-options

    You must set it to false, to allow session cookies on non-https host, or use an https host.

    test code

    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);
    

    output

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

提交回复
热议问题