Koa2经过app.use(function)方法来注册中间件。
全部的http请求都会依次调用app.use()方法,因此中间件的使用顺序很是重要。javascript
官方说明:java
假设依次有 A、B 两个中间件,首先请求流经过 A 中间件,而后继续移交控制给 B 中间件。当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开而且每一个中间件恢复执行其上游行为。node
咱们来作个简单的测试,写三个中间件来测试执行顺序:json
const Koa = require('koa') const app = new Koa() app.use(async (ctx, next) => { console.log('http request 1') await next() console.log('http request end 1') }) app.use(async (ctx, next) => { console.log('http request 2') await next() console.log('http request end 2') }) app.use(async (ctx, next) => { console.log('http request 3') await next() console.log('http request end 3') }) app.listen(8000) module.exports = app
模拟了一个请求以后,能够看到node.js控制台依次输出:浏览器
http request 1 http request 2 http request 3 http request end 3 http request end 2 http request end 1
所以,能够得知官网的意思是:中间件中的方法,会以一个栈结构的顺序来执行,先由上至下依次执行,在遇到await next()方法后,会暂停该中间件的执行,执行下一个中间件,当全部的中间件都执行完毕时,再由下往上依次执行每一个中间件next 后面的方法。bash
知道了中间件的执行原理,写一个中间件就很是简单了。
例如实现一个简单的打印请求耗时的中间件只须要简单的几行代码:app
app.use(async (ctx, next) => { const url = ctx.url const method = ctx.method console.time(`-- ${method} ${url} cost`) await next() console.timeEnd(`-- ${method} ${url} cost`) })
在浏览器发起一个请求localhost:8000?username=zj。
在node.js控制台打印:koa
-- GET /?username=zj cost: 2.337ms -- GET /favicon.ico cost: 0.159ms
能够看到第一个是正常请求的log,第二个是请求图标的log。curl
koa-bodyparser
中间件可以帮咱们自动解析post参数。
经过koa-bodyparser
,咱们可以很方便的在ctx.request.body里面直接获取到解析好的数据。
请看代码:async
const Koa = require('koa') const app = new Koa() const bodyparser = require('koa-bodyparser') app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(async ctx => { const req = ctx.request const url = req.url // 请求的url const method = req.method // 请求的方法 console.log(req.body) ctx.body = req.body }) app.listen(8000) module.exports = app
经过curl模拟请求:
$ curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost:8000
能够看到node.js控制台输出:
{ id: 100 }
koa-router
是一款官方默认的路由中间件,若是咱们本身实现路由的话,可能须要手动去判断请求url,再返回不一样的响应,可是有了koa-router
中间件以后,咱们能够很方便的对路由进行系统化的管理。 具体使用方法咱们在下节再讲。