1、安裝
cnpm install koa koa-router
2、引入koa和router路由
let koa =require('koa');
let koaRouter=require('koa-router');
3、生成應用以及路由器實例
const app=new koa();
const router=new koaRouter();
4、使用路由及其方法
app.use(router.routes()) //聲明使用路由
.use(router.allowedMethods()); //允許使用路由的方法
5、監聽端口
app.listen(3000,()=>{
console.log('this koa server is running at http://127.0.0.1:3000');
})
6、創建get方式路由
router.get('/路由名',(ctx,next)=>{
ctx上下文取代req,res
ctx.request 獲取請求頭等信息
ctx.query.鍵名獲取get請求參數
ctx.body="服務器返回數據";
})
代碼示例:
let koa =require('koa');
let koaRouter=require('koa-router');
//生成應用以及路由器實例
const app=new koa();
const router=new koaRouter();
//使用路由及路由器
app.use(router.routes()) //聲明使用路由
.use(router.allowedMethods()); //允許使用路由的方法
//監聽端口
app.listen(3000,()=>{
console.log('this koa server is running at http://127.0.0.1:3000');
})
//創建路由
//ctx上下文取代req,res
router.get('/',(ctx,next)=>{
//獲取請求參數
//響應數據
ctx.body="服務器返回";
})
router.get('/search',(ctx,next)=>{
let req=ctx.query.id;
let arr=[];
for(let i=0;i<req*5;i++)
{
arr.push(i);
}
ctx.body=arr;
})