我正在使用Express和node通过https进行会话管理。我想使用express创建一个会话,以便在重定向到公用文件夹中的静态文件之前进行身份验证和会话。以前我在使用express.session和https时遇到了麻烦, 但是通过在express.session中将路径包含为/ public来解决了问题,但是现在我的req.session显示为未定义,但是在浏览器中存在connect.sid cookie
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(); });
客户端 :
问题是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'
。我经历了很多问题,但无法弄清楚。
我的网站是静态的,所有* .html都位于公共目录中
会话中间件检查传入的请求是否匹配cookie路径;如果没有,它不会打扰继续(req.session
甚至不会被创建)。根据您的情况,您的Cookie路径设置为/public/
,与请求路径不匹配/login
。
我认为您想配置会话中间件cookie以/
用作路径:
app.use(express.session({ cookie: { path : '/', httpOnly: false, maxAge : 24*60*60*1000 }, secret: '1234567890QWERT' }));