代码语言:javascript复制
npm init -y
npm i -S koa@2
创建app.js文件,代码如下:
代码语言:javascript复制const Koa = require('koa')
const app = new Koa()
app.use(async (ctx,next) => {
const start = new Date()
console.log('[logger middleware] before await ...')
await next()
console.log('[logger middleware] after await ...')
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(async ctx =>{
console.log('[response middleware] response ...')
ctx.body = 'Hello Koa 2'
})
app.listen(3000)
koa V1 和 koa V2的用法差异
koa V1
代码语言:javascript复制var koa = requier('koa');
var app = koa();
koa V2
代码语言:javascript复制const Koa = require('koa');
const app = new Koa();
Koa脚手架 koa-generator
代码语言:javascript复制npm i --global koa-generator
利用koa-generator创建项目
代码语言:javascript复制koa2 helloworld