猫幻  
引入类
const Koa=require('koa');
const koaBody = require('koa-body');
const Router=require('koa-router');
 
创建对象
const app=new Koa();
app.use(koaBody());
const router=new Router();
 
 
get链接
router.get("/",async (ctx)=>{
    //url参数 ctx.query
    console.log(ctx.url);
    console.log(ctx.query);
    // console.log(ctx.querystring);
})
 
// postman 测试后台接口
 
post链接
router.post("/a",async ctx=>{
    console.log(ctx.url);
    console.log(ctx.request.body);
    ctx.body="请求成功";
});
 
// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({
    // throw: true, // 抛出错误,代替设置响应头状态
    // notImplemented: () => '不支持当前请求所需要的功能',
    // methodNotAllowed: () => '不支持的请求方式'
}));
app.listen(3000,()=>{
    console.log("http://localhost:3000")
})
npm i koa-router --save
包npm i koa-body --save
posted on 2021-11-26 12:05  猫幻  阅读(24)  评论(0编辑  收藏  举报