Koa2学习(五)中间件

Koa2学习(五)中间件

Koa2通过app.use(function)方法来注册中间件。
所有的http请求都会依次调用app.use()方法,所以中间件的使用顺序非常重要。

中间件的执行顺序

官方说明:

假设依次有 A、B 两个中间件,首先请求流通过 A 中间件,然后继续移交控制给 B 中间件。当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。


我们来做个简单的测试,写三个中间件来测试执行顺序:

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 后面的方法。

实现一个简单的log time中间件

知道了中间件的执行原理,写一个中间件就非常简单了。
例如实现一个简单的打印请求耗时的中间件只需要简单的几行代码:

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控制台打印:

-- GET /?username=zj cost: 2.337ms
-- GET /favicon.ico cost: 0.159ms

可以看到第一个是正常请求的log,第二个是请求图标的log。

koa-bodyparser

koa-bodyparser中间件能够帮我们自动解析post参数。
通过koa-bodyparser,我们能够很方便的在ctx.request.body里面直接获取到解析好的数据。
请看代码:

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

koa-router是一款官方默认的路由中间件,如果我们自己实现路由的话,可能需要手动去判断请求url,再返回不同的响应,但是有了koa-router中间件之后,我们可以很方便的对路由进行系统化的管理。
具体使用方法我们在下节再讲。

原文地址:https://www.cnblogs.com/shenshangzz/p/9973391.html