koa-router使用

koa-router使用

Koa-router 是 koa 的一个路由中间件,它可以将请求的URL和方法(如:GET 、 POST 、 PUT 、 DELETE 等) 匹配到对应的响应程序或页面。

基本配置

  • 创建Koa应用
 1 // app.js
 2 
 3 const Koa = require('koa'); // 引入koa
 4 
 5 const app = new Koa(); // 创建koa应用
 6 
 7 // 启动服务监听本地3000端口
 8 app.listen(3000, () => {
 9     console.log('应用已经启动,http://localhost:3000');
10 })
  • 安装koa-router

1 $ npm install koa-router --save

 

  • 使用koa-router

const Koa = require('koa'); // 引入koa
const Router = require('koa-router'); // 引入koa-router

const app = new Koa(); // 创建koa应用
const router = new Router(); // 创建路由,支持传递参数

// 指定一个url匹配
router.get('/', async (ctx) => {
    ctx.type = 'html';
    ctx.body = '<h1>hello world!</h1>';
})

// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({ 
    // throw: true, // 抛出错误,代替设置响应头状态
    // notImplemented: () => '不支持当前请求所需要的功能',
    // methodNotAllowed: () => '不支持的请求方式'
}));

// 启动服务监听本地3000端口
app.listen(3000, () => {
    console.log('应用已经启动,http://localhost:3000');
})
  • get post不同请求方式

Koa-router请求方式  get   post,使用方法是 router.get() router.post() 。而  router.all() 会匹配所有的请求方法。

当 URL匹配成功时,router  就会执行对应的中间件来对请求进行处理:

 

 1 router.get("/", async ctx=>{
 2     // url 参数
 3     console.log(ctx.url);
 4     console.log(ctx.query);
 5     // console.log(ctx.querystring);
 6 })
 7 // postman 
 8 router.post("/a",async ctx=>{
 9     console.log(ctx.url);
10     console.log(ctx.request.body)
11     ctx.body="请求成功"
12 })

 

posted @ 2021-11-26 12:18  .Nice  阅读(415)  评论(0)    收藏  举报