nodejs

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

 

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

 

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

 

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

 

})

 

// postman 测试后端接口
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.use(router.routes().use(router.allowedMethods({ }));

 

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

# content
# id=1000&name=张三
{
   "id":1000,
   "name":"张三"
}

 

posted @ 2021-11-26 19:47  牵着宇宙来遛弯  阅读(53)  评论(0)    收藏  举报