1,安装 koa-router
npm install -S koa-router
2,修改index.js
const Koa=require('koa');
const Router=require('koa-router')
const app=new Koa();
const router=new Router()
router.get('/',ctx=>{
console.log(ctx.request);
ctx.body='Hello World!';
})
router.get('/api',ctx=>{
console.log(ctx.request);
ctx.body='Hello Api!';
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(3000);
async/await 使用同步代码修改
const Koa=require('koa');
const Router=require('koa-router')
const app=new Koa();
const router=new Router()
router.get('/',ctx=>{
console.log(ctx.request);
ctx.body='Hello World!';
})
router.get('/api',ctx=>{
console.log(ctx.request);
ctx.body='Hello Api!';
})
router.get('/async',async (ctx)=>{
let result=await new Promise((resolve => {
setTimeout(function() {
resolve('hello world 2s later')
},2000)
}))
ctx.body=result;
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(3000);
插件
koa-router
https://www.npmjs.com/package/koa-router
koa-body
实现文件上传
https://www.npmjs.com/package/koa-body
网友评论