midwayjs / midway

🍔 A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. 🌈
https://www.midwayjs.org/
MIT License
7.34k stars 573 forks source link

全局中间件2种使用方法表现不一致的问题 #833

Closed tanggd closed 3 years ago

tanggd commented 3 years ago

初学者,跟着文档学的,https://www.yuque.com/midwayjs/midway_v2/web_middleware, 发现全局中间件2种使用方法表现不一致的问题。

全局中间件:

// src/middleware/global.ts
import { Provide } from "@midwayjs/decorator";
import { IMidwayWebNext, IWebMiddleware } from "@midwayjs/web";
import { Context } from "egg";

@Provide()
export class GlobalMiddleware implements IWebMiddleware {
  resolve() {
    return async (ctx: Context, next: IMidwayWebNext) => {
      console.log('全局中间件,前面')
      await next()
      console.log('全局中间件,后面')
    }
  }
}

使用方法1: 直接在 src/configuration.ts 中使用

// src/configuration.ts
import { ILifeCycle } from '@midwayjs/core';
import { App, Configuration } from '@midwayjs/decorator';
import { Application } from 'egg';

@Configuration()
export class ContainerLifeCycle implements ILifeCycle {

  @App()
  app: Application;

  async onReady() {
    this.app.use(await this.app.generateMiddleware('globalMiddleware'))
  }
}

现象是:GlobalMiddleware 中的 console.log() 各打印了2次,这样的表现是个bug。

使用方法2: 在 src/config/config.default.ts 中配置 middleware 属性

// src/config/config.default.ts
import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg';

export type DefaultConfig = PowerPartial<EggAppConfig>;

export default (appInfo: EggAppInfo) => {
  const config = {} as DefaultConfig;

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

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

  return config;
};

现象是:GlobalMiddleware 中的 console.log() 各打印了1次,属于正常情况。

czy88840616 commented 3 years ago

image 似乎没有出现?

tanggd commented 3 years ago

image 似乎没有出现?

第一次访问确实是正常的,但是刷新页面就出现问题了

czy88840616 commented 3 years ago

image

其实是正常的,因为浏览器会自动发出一个 /favicon 的请求。

tanggd commented 3 years ago

image

其实是正常的,因为浏览器会自动发出一个 /favicon 的请求。

原因确实是它,但直接在 src/config/config.default.ts 中使用,就不会出现这种问题。似乎忘了我自己的要问的问题了,我的问题是两种全局中间件使用方法的表现不一致的问题。是不是应该设计成一致性的?

waitingsong commented 3 years ago

如果网站没有 /favicon.ico 图片,那么浏览器似乎每次请求都会发一个对这个地址的请求

czy88840616 commented 3 years ago

@tanggd 应该是 egg 默认提供了 siteFile 中间件处理了 /favicon 请求,onReady 里的 app.use 是 koa 的标准用法,我们这里扩展是为了适配不同的场景框架,会默认在 egg 之前执行,在 egg 下建议不要使用这个地方去加载中间件(而是用 egg 自带的用法),我会在文档做说明。