zoukankan      html  css  js  c++  java
  • 一、eggjs学习记录

    eggjs的中间件分为全局中间件和router中间件。

    全局中间件用法:

    // app/middleware/requestTime.js
    module.exports = () => {
    
        return async (ctx: any, next: any) => {
    
            ctx.requestBeginTime = +new Date();
            await next();
           
    
        };
    };
    //中间件写法一致,都是返回一个async函数,然后async函数的参数包括: ctx、next。

     全局中间件调用和配置方法:

    // app/config/config_base.js
    import { join } from 'path';
    module.exports = {
        
        // 中间件
        //可以在配文件中按顺序写需要调用的中间件,参考洋葱圈模型 
        middleware: ['requestTime', 'errorHandler', 'koaStatic'],
        //如果中间件需要参数可以在这里配置,比如:
        koaStatic: join(__dirname, 'dist')
        
    };

    router中间件

    // app/middleware/headerParse.js
    module.exports = () => {
        return async (ctx: any, next: any) => {
            
            // 获取 params ,只能在router中才有这个数据,全局中间件是没有这个的
            let activityId = ctx.params.activityId;
    
            const requestParams = {
                activityId
            };
            ctx.request.requestParams = requestParams;
            await next();
        };
    };

    router中间件调用:

    // app/router.ts
    import { Application } from 'egg';
    
    export default (app: Application) => {
        const {
            router,
            controller,
            middlewares,
        } = app;
    
        
        router.get('/promotion/babelpc/:activityId', middlewares.headerParser(), controller.activity.render);
        
    };
  • 相关阅读:
    肥胖儿筛选标准
    文章索引
    面向对象66原则
    [精]Xpath路径表达式
    [精]XPath入门教程
    孕产期高危因素
    “华而不实”的转盘菜单(pie menu)
    xmind用例导excel用例,然后再用python排版
    NSObject
    [self class]与[super class]
  • 原文地址:https://www.cnblogs.com/hellolol/p/11507858.html
Copyright © 2011-2022 走看看