HELP...Refresh the page after login, session disappears
zzyxka opened this issue · comments
Fizzy commented
Page running 127.0.0.1:3000
Server running 127.0.0.1:8888
page request code:
await axios.get(`${host}${path}`, { params: params, withCredentials: true });
Refresh the page after login, session disappears.
router.post('/', async ctx => {
const { db } = ctx;
try {
const { username, password } = ctx.request.fields;
const userList = await db.query('SELECT * FROM user WHERE username = ? AND password = ?', [username, password]);
if (userList.length > 0) {
ctx.session['userId'] = userList[0].id;
console.log('ctx.session: ', ctx.session);
ctx.body = { code: 0 }
} else {
ctx.body = { code: -1, msg: '登录失败,用户不存在或密码错误!' };
}
} catch (e) {
console.log(e);
}
});
// 处理跨域
server.use(cors({
credentials: true, //带cookies
}));
// session处理
server.keys = ['asdasdasdasgfsdg'];
server.use(session({
maxAge: 3 * 24 * 60 * 60 * 1000,
rolling: true,
renew: true
}, server));
const sessionDeal = require('./lib/check-user.js');
server.use(async (ctx, next) => sessionDeal(ctx, server, next));
/**
* /lib/check-user.js [sessionDeal]
* 通用校验是否登录成功的合法用户
*/
module.exports = async (ctx, server, next) => {
if (!ctx.path.includes('/user/login')) {
console.log('ctx.cookie: ', ctx.cookies);
console.log('ctx.session: ', ctx.session);
const { userId } = ctx.session;
if (userId && Number(userId) > 0) {
server.context.userId = userId;
await next();
} else {
// 401 无权访问需登录
ctx.throw(401, {
code: 1,
msg: '请先登录'
});
}
} else {
await next();
}
};