koa-custom middleware

Insert picture description here

Prepare in advance
1、初始化项目 npm init 

2、安装依赖 cnpm install -g koa-generator 

3、进入项目并安装依赖  cd koaProject & cnpm i 

4、启动项目 npm start koaProject 

注意这里用的淘宝的镜像源
Custom middleware

自定义中间件的话一般是创建一个js文件,在app.js中引入并使用,如下所示

function pv(ctx) {
    
    

    //do something  Write your code logic
    
    global.console.log(ctx.path);
    
    global.console.log('this is define middleware')
}

module.exports = () => {
    
    

    return async(ctx, done) => {
    
    
    
        pv(ctx);
        
        await done();
    }
}

在app.js引入并使用

const pv = require('./middleware/koa-pv')//引入

app.use(pv())///使用

Thank you for watching, if there are any shortcomings, please advise

Guess you like

Origin blog.csdn.net/handsomezhanghui/article/details/108082727