javascript req.session 未定义和 req.session.user_id 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21093787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:01:44  来源:igfitidea点击:

req.session undefined and req.session.user_id not working

javascriptnode.jssessioncookiesexpress

提问by Zeeshan

I am using Express and node for the session management with https. I want to create a session using express so that authentication and the session is made before the redirection to the static files in the public folder. Previously i was having a problem Trouble using express.session with httpsBut it was solved by including path in the express.session as /public but now my req.session is showing as undefined but in the browser there is connect.sid cookie present

我正在使用 Express 和 node 进行 https 会话管理。我想使用 express 创建一个会话,以便在重定向到公共文件夹中的静态文件之前进行身份验证和会话。以前我遇到了一个问题使用带有 https 的 express.session时遇到问题 但是通过在 express.session 中包含路径作为 /public 解决了这个问题,但现在我的 req.session 显示为未定义但在浏览器中存在 connect.sid cookie

The app.js is :

app.js 是:

var express = require('express')TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:59:24 at callbacks;
var http = require('http');
var https = require('https');
var fs = require('fs');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/svgtest1');
var options = {
  key: fs.readFileSync('privatekey.pem'),
  cert: fs.readFileSync('certificate.pem')
};

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded());
app.use(express.json());
app.use(express.cookieParser());
app.use(express.session({cookie: {  path: '/public/',httpOnly: false , maxAge: 24*60*60*1000}, secret: '1234567890QWERT'}));

//middle ware to check auth
function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.send('You are not authorized to view this page');
  } else {
    next();
  }
}


app.get('/', function(req, res) {
  console.log('First page called');
  res.redirect('loginform.html');
  console.log('redirected');
  res.end();
});

app.post('/login', function(req, res) {
  console.log('login called');
  var usrfield = req.body.usrfield;
  var passfield = req.body.passfield;

    console.log(req.session);


// Play with the username and password

        if (usrfield == 'kk' && passfield == '123') {
             req.session.user_id = 'xyz';
        res.redirect('svg-edit.html');
      } else {
        res.send('Bad user/pass');
      }


        console.log(usrfield);
        console.log(passfield);
        res.end();
    });

Client Side :

客户端 :

<html>

<style media="screen" type="text/css">
@import url("css/loginform_styles.css");
 </style>

    <head>
            <script type="text/javascript" src="annotationTools/js/md5.js" ></script>
            <script>

                function validateForm()
                {
                    var usrnamefield=document.forms["loginform"]["usrfield"].value;
                    var passwrdfield=document.forms["loginform"]["passfield"].value;

                    if ((usrnamefield==null || usrnamefield=="")||(passwrdfield==null || passwrdfield==""))
                      {
                        document.getElementById('valueerrorlayer').innerHTML ='Username or password field is empty';
                        //document.forms["loginform"]["errorshow"].innerHtml = 'username or password empty';
                      return false;
                      }
                    else return true;
                }
            </script>

    </head>

    <body>


    <form name="loginform" id="loginform" action="https://localhost:8888/login" method="post" onsubmit="return validateForm()">
        <div id = "content" align = "center">

            <p align="center"><font size="7">LabelMe Dev</font></p> 
            <br />
            <br />

            <label> Please Enter the <b><i>Username</i></b></label>
            <br />
            <br />

            <input type="text"  name = "usrfield" id = "usrfield" onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()"/>
            <br />
            <br />
            <br />

            <label> Please Enter the <b><i>Password</i></b></label>
            <br />
            <br />
            <input type="password"  name = "passfield" id = "passfield" onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()"/>
            <br />
            <br />
            <br />

            <i><p id='valueerrorlayer' style="color:red;"> </p></i>

            <input type="submit" value="Submit"/>
        </div>
    </form>     
    </body>





</html>

The problemis that console.log(req.session);gives undefined so the req.session.user_id = 'xyz';also not works and error 'TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:59:24 at callbacks'comes. I have gone through many questions but was not able to figure out.

问题console.log(req.session);给出了 undefined 所以req.session.user_id = 'xyz';也不起作用并且错误'TypeError: Cannot set property 'user_id' of undefined at /opt/expressjs/app.js:59:24 at callbacks'来了。我经历了很多问题,但无法弄清楚。

My website is static and all the *.html locates in the public directory

我的网站是静态的,所有的 *.html 都位于公共目录中

回答by robertklep

The session middleware checks if an incoming request matches the cookie path; if not, it doesn't bother continuing (and req.sessionwon't even be created). In your situation, your cookie path is set to /public/, which doesn't match the request path /login.

会话中间件检查传入请求是否与 cookie 路径匹配;如果没有,它不会打扰继续(req.session甚至不会被创建)。在您的情况下,您的 cookie 路径设置为/public/,这与请求路径不匹配/login

I think you'd want to configure the session middleware cookie to use /as a path:

我认为您希望将会话中间件 cookie 配置/为用作路径:

app.use(express.session({
  cookie: {
    path    : '/',
    httpOnly: false,
    maxAge  : 24*60*60*1000
  },
  secret: '1234567890QWERT'
}));