How eggjs uses session to control user login

when the user logs in with eggjs, and after the user has successfully logged in, put user in session

async login() {
    const ctx = this.ctx;
    const { username, password } = ctx.request.body;
    const user = await this.service.home.login(username, password);
    ctx.session.user = user;
    const { id, schemastr } = user || {};
    console.log(ctx.session);
    ctx.body = {
      data: {
        id,
        schemastr,
        username,
      },
      message: "success",
    };
 }
 

the problem is that after setting session, the session of other controller functions is empty:

async asyncData() {
    const ctx = this.ctx;
    const { id, schemastr } = ctx.request.body;
    this.service.home.asyncData(id, schemastr);
    console.log(ctx.session); // => {}
    ctx.body = {
      data: 200,
      message: "success",
    };
 }
 
May I ask what happened to everyone?

Mar.14,2021

this is because there is no serialization or serialization to session failed
if in express is:

passport.serializeUser((user, done) => {
        done(null, user.id);
});

if passport is packaged by egg-passport in egg.js
you need to do it in app.js:

passport.serializeUser(async(ctx, user) => {
    return user; 
    // ctx.session.passport.user  ctx.user
    //  'return user', ctx.user  undefined
});

https://eggjs.org/zh-cn/tutor.

Menu