eggjs 无法获取到 session 问题

2,263 阅读2分钟

近期在做 胖哥的博客项目,遇到一个 eggjs 的坑

后台接口配置:

// src/config/apiUrl.js

let ipUrl = 'http://127.0.0.1:7001/admin/'

let servicePath = {
  getTypeInfo: ipUrl + 'getTypeInfo',  //  获得文章类别信息
  checkLogin: ipUrl + 'checkLogin',  //  检查用户名密码是否正确
  addArticle:ipUrl + 'addArticle' ,  //  添加文章
  updateArticle:ipUrl + 'updateArticle' ,  //  修改文章第api地址

}
export default servicePath;

server 端 eggjs 配置

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1606377868008_4639';

  // add your middleware config here
  config.middleware = [
    
  ];

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  config.mysql = {
    client: {
      // ...
  }


  config.security = {
    csrf: {
      enable: false
    },
    domainWhiteList: ['*']
  };
  config.cors = {
    credentials: true,  // 允许Cook可以跨域
    origin: 'http://localhost:3000', //只允许这个域进行访问接口
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
  };

  return {
    ...config,
    ...userConfig,
  };
};

设置 session

async checkLogin() {
    let userName = this.ctx.request.body.userName
    let password = this.ctx.request.body.password
    const sql = " SELECT name FROM users WHERE name = '" + userName +
      "' AND password = '" + password + "'"

    const res = await this.app.mysql.query(sql)
    console.log('res: ', res);
    if (res.length > 0) {
      //登录成功,进行session缓存
      let openId = new Date().getTime()
      this.ctx.session.openId =  openId
      this.ctx.body = { 'data': '登录成功', 'openId': openId }
      console.log('this.ctx.session', this.ctx.session);
    } else {
      this.ctx.body = { data: '登录失败' }
    }
  }

中间件取 session

// /middleware/adminauth.js
module.exports = options => {
  return async function adminauth(ctx, next) {
    console.log('ctx.session.openId----', ctx.session);

    // 这里死活拿不到 session.openId
    if (ctx.session.openId) {
      await next();
    } else {
      ctx.body = {
        data: '未登录',
      };
    }
  };
};

路由中使用 中间件

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {

  const { router, controller } = app
  const adminauth = app.middleware.adminauth();
  router.post('/admin/checkLogin', controller.admin.main.checkLogin)
  
  // 接口直接报错 未登录
  router.get('/admin/getTypeInfo', adminauth, controller.admin.main.getTypeInfo)
};

通过 server 端配置可以看到,允许跨域的 ip 为 http://localhost:3000 ,而 后台启动的地址也确实是在这个地址上,但是这样拿不到 session,debug 半天和看文档,没整明白,后面查到原因居然是因为 前端请求地址问题

后台接口代码应该为:

// src/config/apiUrl.js
// 这里不一样
// let ipUrl = 'http://127.0.0.1:7001/admin/'
let ipUrl = 'http://localhost:7001/admin/'

let servicePath = {
  // ...

}
export default servicePath;

参考资料: