2021.11.26

//引入对象
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');
//引入内部方法或属性
// constant{方法或者属性名} = require('koa');


// 创建对象
const app = new Koa();

app.use(koaBody());
const router = new Router();//创建路由 支持传递参数

// response
// app.use(async (ctx,next) => {
//     ctx.body = 'Hello World';
//     next();
//   });

  router.get("/", async ctx=>{
    //url参数 ctx.query
    console.log(ctx.url)
    console.log(ctx.query);
    // console.log(ctx.querystring);
  })

  //postam
  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: () => '不支持的请求方式'




// localhost:3000
app.listen(8000,()=>{
  console.log("http://localhost:8000")
});
 
 
 
POST http://localhost:8000/a
Content-Type: application/json

#content
# id=1000&name=张三
{
   "id":1000,
    "name":"张三"
}
 
 
posted on 2021-11-26 12:18  闲鱼仔  阅读(26)  评论(0)    收藏  举报