# router 路由

路由的使用如下:

router.get('/add', (ctx, res, next, services) => {
    let projectService = services.project;
    // do something with service
    res.json({data: {message: "hello, world"}})
})

ctx: 上下文,context对象 res: 响应,resposne对象 next: services: 服务的集合

# 动态路由

一个“路径参数”使用冒号 : 标记,可以通过req.params获取动态参数

router.get("/test/param/:page", (ctx, res, next) => {
  res.json({ result: ctx.params.page });
});

# 请求数据获取

地址参数获取

router.get("/goods", (ctx, res, next) => {
  res.json({ result: ctx.query.page });
});

请求GET /goods?page=1

{ result: 1 }

动态路由参数获取

router.get("/goods/:id", (ctx, res, next) => {
  res.json({ result: ctx.params.id });
});

请求GET /goods/234?page=1

{ result: 234 }

post数据获取

router.post("/goods/:id", (ctx, res, next) => {
  res.json({ result: ctx.body.name });
});

POST请求 {"Content-Type": "application/json"}{"Content-Type": "application/x-www-form-urlencoded"},都可以通过ctx.body获取

cookie获取

router.get("/test/get_cookie", (ctx, res, next) => {
  res.json({ result: ctx.cookies.get("name") });
});

# Service 注入

路由里可以接受 service 的实例

import {router} from "kidi"; router.get('/add', (ctx, res, next, services) => { let projectService = services.project; // do something with service res.json({data: {message: "hello, world"}}) })