session登录态判断处理

使用session中间件

  1. // code ...
  2. const session = require('koa-session-minimal')
  3. const MysqlStore = require('koa-mysql-session')
  4. const config = require('./../config')
  5. // code ...
  6. const app = new Koa()
  7. // session存储配置
  8. const sessionMysqlConfig= {
  9. user: config.database.USERNAME,
  10. password: config.database.PASSWORD,
  11. database: config.database.DATABASE,
  12. host: config.database.HOST,
  13. }
  14. // 配置session中间件
  15. app.use(session({
  16. key: 'USER_SID',
  17. store: new MysqlStore(sessionMysqlConfig)
  18. }))
  19. // code ...
  1. let session = ctx.session
  2. session.isLogin = true
  3. session.userName = userResult.name
  4. session.userId = userResult.id

需要判断登录态页面进行session判断

  1. async indexPage ( ctx ) {
  2. // 判断是否有session
  3. if ( ctx.session && ctx.session.isLogin && ctx.session.userName ) {
  4. const title = 'work页面'
  5. await ctx.render('work', {
  6. title,
  7. })
  8. } else {
  9. // 没有登录态则跳转到错误页面
  10. ctx.redirect('/error')
  11. }
  12. },