1. import { Provide, Config, ALL } from '@midwayjs/decorator';
    2. import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
    3. import { Context } from 'egg';
    4. import { MyConfig } from '../config/types';
    5. @Provide()
    6. export class ContentPathMiddleware implements IWebMiddleware {
    7. @Config(ALL)
    8. config: MyConfig;
    9. resolve() {
    10. return async (ctx: Context, next: IMidwayWebNext) => {
    11. const { contextPath } = this.config;
    12. if (contextPath) {
    13. const reg = new RegExp(contextPath);
    14. const { url } = ctx.req;
    15. if (reg.test(url)) {
    16. // 去掉 content path
    17. const path = ctx.req.url.replace(reg, '');
    18. // console.log('去掉 contentPath > ', path);
    19. if (path) ctx.req.url = path;
    20. }
    21. }
    22. const { url, method, httpVersion, headers = {} } = ctx.req;
    23. const { body } = ctx.request;
    24. console.log( '>>> ', method, httpVersion, headers['content-type'], url, JSON.stringify(body) );
    25. await next();
    26. console.log( '<<< ', method, ctx.response.headers['content-type'], url, JSON.stringify(ctx.body) );
    27. };
    28. }
    29. }