双越老师,我配置完session以后,用app.post(’/login’…)接口进行登录验证,登陆成功然后req.session.username加入data[0].username(这里是lisi),这时console.log(req.session)里面有username:lisi,但我在浏览器进入/text的路径后,显示未登录,然后console.log(req.session.username)显示的是undefind(如图3第一行,当然console.log(req.session)也显示根本没加进去),但奇怪的是我又写了一个post的接口(app.post(’/exec’…)这个接口),用postman试验,显示的是已登录,console.log(req.session)username:lisi是存在的,如图二,这是为什么,好几天都没找到原因,请双越老师指点,谢谢
const express = require(‘express’);
const getLogin = require(’./getData’);
var cookieParser = require(‘cookie-parser’);
var session = require(‘express-session’);
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret: ‘michael_qin#’,
cookie: {
path: ‘/’,
httpOnly: true,
MaxAge: 1000 * 60 * 60 * 24
}
}))
app.post(’/login’, (req, res) => {
const username = req.body.username;
const password = req.body.password;
getLogin(username, password).then(data => {
console.log(data);
console.log(data[0]);
if (data[0]) {
req.session.username = data[0].username;
console.log(req.session);
console.log(req.session.username);
res.send(‘登陆成功’);
} else {
res.send(‘登陆失败’);
}
});
});
app.post(’/exec’, (req, res) => {
console.log(req.session);
if (req.session.username) {
res.send(‘已登录’);
} else {
res.send(‘未登录’);
}
});
app.get(’/text’, (req, res) => {
console.log(req.session.username);
console.log(req.session);
if (req.session.username) {
res.send(‘已登录’);
} else {
res.send(‘未登录’);
}
});
app.listen(3000, () => {
console.log(‘服务器已经启动’);
});