Koa需要 node v7.6.0
或更高版本来支持ES2015、异步方法
npm install -S koa
app.use
app.listen
如下为一个绑定3000端口的简单 Koa 应用,其创建并返回了一个 HTTP 服务器,为 Server#listen() 传递指定参数(参数的详细文档请查看nodejs.org)。
const Koa = require('koa')
const app = new Koa()
app.listen(3000)
const Koa = require('koa')
const app = new Koa()
const middleware = function async (ctx, next) {
console.log('this is a widdleware')
console.log(ctx.request.path)
next()
}
const middleware1 = function async (ctx, next) {
console.log('this is a widdleware1')
console.log(ctx.request.path)
next()
console.log(1111111)
}
const middleware2 = function async (ctx, next) {
console.log('this is a widdleware2')
console.log(ctx.request.path)
next()
console.log(22222)
}
const middleware3 = function async (ctx, next) {
console.log('this is a widdleware3')
console.log(ctx.request.path)
next()
console.log(3333)
}
app.use(middleware)
app.use(middleware1)
app.use(middleware2)
app.use(middleware3)
app.listen(3000)
打印
this is a widdleware
/
this is a widdleware1
/
this is a widdleware2
/
this is a widdleware3
/
3333
22222
1111111
this is a widdleware
/favicon.ico
this is a widdleware1
/favicon.ico
this is a widdleware2
/favicon.ico
this is a widdleware3
/favicon.ico
3333
22222
1111111
Koa 的中间件通过一种更加传统(您也许会很熟悉)的方式进行级联,摒弃了以往 node 频繁的回调函数造成的复杂代码逻辑。 然而,使用异步函数,我们可以实现"真正" 的中间件。与之不同,当执行到 yield next 语句时,Koa 暂停了该中间件,继续执行下一个符合请求的中间件(‘downstrem’),然后控制权再逐级返回给上层中间件(‘upstream’)。
koa-router
npm install -S koa-router
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
router.get('/', ctx => {
console.log('ctx', ctx)
ctx.body = 'Hello World'
})
// 路由定义的方法定义到koa应用中
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000)
@koa/cors
npm install -S @koa/cors
const cors = require('@koa/cors')
app.use(cors())
koa-compress
koa-static
npm install -S koa-static
const path = require('path')
const staticServer = require('koa-static')
app.use(staticServer(path.join(__dirname, 'static')))
npm install koa-json -S
const json = require('koa-json')
// 请求上拼接pretty时格式化
app.use(json({ pretty: false, param: 'pretty'}))
npm install koa-body -S
const koabody = require('koa-body')
app.use(koabody())
koa-logger