加载时无法访问会话数据,但在 node.js 中重新加载同一页面时可以正常访问
Session data could not be access on loading but fine when reload the same page in node.js
我是 node.js 中使用会话身份验证的初学者。它在我的水平上几乎可以正常工作,
- 用户登录时会话已初始化
- 会话在登录时存储在数据库中,在注销时被删除。
- 会话在我想要的时间段内过期。
- 问题:我想通过
res.render('admin',{user})
在视图中呈现用户电子邮件,但它在加载(登录)时消失,并在我重新加载相同的视图页面时立即出现。加载时 routes/pages.js 中的条件 if(req.session.userEmail)
似乎是 false
但 true
重新加载同一页面时。简而言之,在 routes/pages.js 中加载 else
部分仅可查看,但在 [=24= 下重新加载内容时] 在客户端查看。为什么它出现在重新加载而不是加载时?请帮忙
- routes/pages.js
const express= require('express');
const { removeAllListeners } = require('nodemon');
const router=express.Router();
router.get('/views/admin', (req, res)=>{
console.log(req.session);
if(req.session.userEmail){
res.render('admin', {user});
}else{
res.send('<p>Session Expired. Click <a href="/views/login">here</a> to login</p>');
}
});
**
- 登录加载
**
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
sameSite: true
}
}
- 重新加载登录
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
sameSite: true
},
userEmail: 'pdm@gmail.com'
}
- routes/auth.js
const express= require('express');
const authController= require('../controller/auth');
const router= express.Router();
router.post('/signup',authController.signup);
router.post('/login',authController.login);
router.post('/logout',authController.logout);
module.exports=router;
`
- controller/auth.js
const router = require('../routes/auth');
const bycrypt= require('bcryptjs');
exports.login= (req, res)=>{
const {email,password}=req.body;
myPool.query('SELECT*FROM userinfo WHERE uemail=?' ,[email],(err,rows,fields)=>{
if(err){
console.log(err);
}else if(rows.length>0){
bycrypt.compare(password,(rows[0].upwd),(err,success)=>{
if(err){
console.log(err);
}else{
console.log(success);//print fine
if(success==false||rows[0].uemail!==email){
return res.render('login',{
message:'Incorrect Password'
});
}else {
var sessUser=req.session;
sessUser.userEmail=email;
console.log(sessUser.userEmail)//print fine
if(sessUser.userEmail){
res.redirect('../views/admin');
}
}
}
})
}else{
return res.render('login',{
message:'This Email does not exist'
})
}
});
}
- 日志
true
pdm@gmail.com
index.js
const express = require('express');
const session = require('express-session');
const mySqlStore = require('express-mysql-session')(session);
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const dotenv = require('dotenv');
const {
request
} = require('https');
const app = express();
app.use((req, res, next) => { console.log(req.url, req.session && req.session.userEmail); next();})//it print current 'url' and 'undefined'
dotenv.config({
path: './.env'
});
const options = {
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'logindb',
createDatabaseTable: true
}
myPool = mysql.createPool(options);
const sessionStore = new mySqlStore(options, myPool);
app.use(session({
name: process.env.SESS_NAME,
secret: 'my secret',
saveUninitialized: false,
resave: true,
store: sessionStore,
cookie: {
maxAge: 10 * 60 * 1000,
httpOnly: true,
sameSite: true
}
}));
const publicDirectory = path.join(__dirname, './public');
app.use(express.static(publicDirectory));
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.set('view engine', 'hbs');
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(8084, () => console.log('Server is running at port:8084'));
exports.store = sessionStore;
- 所有日志
Server is running at port:8084
---before login---
/views/login undefined
/style.css undefined
---On login---
/auth/login undefined
/views/admin undefined
---On reload after login---
/views/admin undefined
/style.css undefined
---On logout---
/auth/logout undefined
/views/login undefined
/style.css undefined
不清楚发生了什么。这可能是一个时间问题,登录后的重定向在会话数据成功保存到数据库之前返回到您的服务器。您可以通过更改此来消除这种可能性:
var sessUser=req.session;
sessUser.userEmail=email;
console.log(sessUser.userEmail)//print fine
if(sessUser.userEmail){
res.redirect('../views/admin');
}
对此:
var sessUser = req.session;
sessUser.userEmail = email;
console.log(sessUser.userEmail);
req.session.save((err) => {
if (err) {
console.log("session save error", err);
res.sendStatus(500);
} else {
res.redirect('../views/admin');
}
});
我是 node.js 中使用会话身份验证的初学者。它在我的水平上几乎可以正常工作,
- 用户登录时会话已初始化
- 会话在登录时存储在数据库中,在注销时被删除。
- 会话在我想要的时间段内过期。
- 问题:我想通过
res.render('admin',{user})
在视图中呈现用户电子邮件,但它在加载(登录)时消失,并在我重新加载相同的视图页面时立即出现。加载时 routes/pages.js 中的条件if(req.session.userEmail)
似乎是false
但true
重新加载同一页面时。简而言之,在 routes/pages.js 中加载else
部分仅可查看,但在 [=24= 下重新加载内容时] 在客户端查看。为什么它出现在重新加载而不是加载时?请帮忙 - routes/pages.js
const express= require('express');
const { removeAllListeners } = require('nodemon');
const router=express.Router();
router.get('/views/admin', (req, res)=>{
console.log(req.session);
if(req.session.userEmail){
res.render('admin', {user});
}else{
res.send('<p>Session Expired. Click <a href="/views/login">here</a> to login</p>');
}
});
- 登录加载
**
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
sameSite: true
}
}
- 重新加载登录
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
sameSite: true
},
userEmail: 'pdm@gmail.com'
}
- routes/auth.js
const express= require('express');
const authController= require('../controller/auth');
const router= express.Router();
router.post('/signup',authController.signup);
router.post('/login',authController.login);
router.post('/logout',authController.logout);
module.exports=router;
`
- controller/auth.js
const router = require('../routes/auth');
const bycrypt= require('bcryptjs');
exports.login= (req, res)=>{
const {email,password}=req.body;
myPool.query('SELECT*FROM userinfo WHERE uemail=?' ,[email],(err,rows,fields)=>{
if(err){
console.log(err);
}else if(rows.length>0){
bycrypt.compare(password,(rows[0].upwd),(err,success)=>{
if(err){
console.log(err);
}else{
console.log(success);//print fine
if(success==false||rows[0].uemail!==email){
return res.render('login',{
message:'Incorrect Password'
});
}else {
var sessUser=req.session;
sessUser.userEmail=email;
console.log(sessUser.userEmail)//print fine
if(sessUser.userEmail){
res.redirect('../views/admin');
}
}
}
})
}else{
return res.render('login',{
message:'This Email does not exist'
})
}
});
}
- 日志
true
pdm@gmail.com
index.js
const express = require('express');
const session = require('express-session');
const mySqlStore = require('express-mysql-session')(session);
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const dotenv = require('dotenv');
const {
request
} = require('https');
const app = express();
app.use((req, res, next) => { console.log(req.url, req.session && req.session.userEmail); next();})//it print current 'url' and 'undefined'
dotenv.config({
path: './.env'
});
const options = {
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'logindb',
createDatabaseTable: true
}
myPool = mysql.createPool(options);
const sessionStore = new mySqlStore(options, myPool);
app.use(session({
name: process.env.SESS_NAME,
secret: 'my secret',
saveUninitialized: false,
resave: true,
store: sessionStore,
cookie: {
maxAge: 10 * 60 * 1000,
httpOnly: true,
sameSite: true
}
}));
const publicDirectory = path.join(__dirname, './public');
app.use(express.static(publicDirectory));
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.set('view engine', 'hbs');
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(8084, () => console.log('Server is running at port:8084'));
exports.store = sessionStore;
- 所有日志
Server is running at port:8084
---before login---
/views/login undefined
/style.css undefined
---On login---
/auth/login undefined
/views/admin undefined
---On reload after login---
/views/admin undefined
/style.css undefined
---On logout---
/auth/logout undefined
/views/login undefined
/style.css undefined
不清楚发生了什么。这可能是一个时间问题,登录后的重定向在会话数据成功保存到数据库之前返回到您的服务器。您可以通过更改此来消除这种可能性:
var sessUser=req.session;
sessUser.userEmail=email;
console.log(sessUser.userEmail)//print fine
if(sessUser.userEmail){
res.redirect('../views/admin');
}
对此:
var sessUser = req.session;
sessUser.userEmail = email;
console.log(sessUser.userEmail);
req.session.save((err) => {
if (err) {
console.log("session save error", err);
res.sendStatus(500);
} else {
res.redirect('../views/admin');
}
});