Recently, I encountered an eggJS pit while working on my blog project

Background interface configuration:

// src/config/apiUrl.js

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

let servicePath = {
  getTypeInfo: ipUrl + 'getTypeInfo'.// Get the article category information
  checkLogin: ipUrl + 'checkLogin'.// Check whether the user name and password are correct
  addArticle:ipUrl + 'addArticle' ,  // Add the article
  updateArticle:ipUrl + 'updateArticle' ,  // Change the API address of the article

}
export default servicePath;

Copy the code

Eggjs is configured on the server

'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: [The '*']}; config.cors = {credentials: true.// Allow Cook to cross domains
    origin: 'http://localhost:3000'.// Only this domain is allowed to access the interface
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
  };

  return{... config, ... userConfig, }; };Copy the code

Set up the 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) {
      // The login succeeds, and the session cache is performed
      let openId = new Date().getTime()
      this.ctx.session.openId =  openId
      this.ctx.body = { 'data': 'Login successful'.'openId': openId }
      console.log('this.ctx.session'.this.ctx.session);
    } else {
      this.ctx.body = { data: 'Login failed'}}}Copy the code

Middleware Session fetch

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

    // There is no session.openId available
    if (ctx.session.openId) {
      await next();
    } else {
      ctx.body = {
        data: 'Not logged in'}; }}; };Copy the code

Middleware is used in routing

/ * * *@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)
  
  // The interface reported an error and failed to log in
  router.get('/admin/getTypeInfo', adminauth, controller.admin.main.getTypeInfo)
};
Copy the code

As can be seen from the server configuration, the IP address allowed to cross domains is http://localhost:3000, and the background startup address is indeed at this address, but it is not clear that session, debug and document can not be obtained for a long time. Back to check the reason was actually because of the front-end request address problem

The background interface code should be:

// src/config/apiUrl.js
// It's different here
/ / let ipUrl = 'http://127.0.0.1:7001/admin/'
let ipUrl = 'http://localhost:7001/admin/'

let servicePath = {
  // ...

}
export default servicePath;

Copy the code

References:

  • About the reason why egg.js cannot obtain session and cookie in middleware
  • Eggjs- Middleware