03-Koa-处理路由

229 阅读1分钟

老样子,安装包

npm install koa-router

详情: www.npmjs.com/package/koa…

但是npm地址没有使用教程,教程推荐这个地址: github.com/ZijianHe/ko…

废物不多说,直接上代码

const Koa = require("koa");
// 导入处理路由的模块
const Router = require("koa-router");
const app = new Koa();
// 创建路由对象
const router = new Router();
// 处理路由
/*
- 接收两个参数
  + 第一个参数: 路由地址
  + 第二个参数: 接收一个回调函数(ctx和next)
- koa中响应数据是通过上下文ctx的body属性来进行响应的
- 同样也可以返回JSON
 */
router.get("/api", (ctx, next) => {
  ctx.body = "get成功响应字符串";
});
router.get("/list", (ctx, next) => {
  ctx.body = {
    name: "sandy",
    age: 21,
    method: "get",
  };
});
router.post("/registered", (ctx, next) => {
  ctx.body = "post成功响应字符串";
});
router.post("/login", (ctx, next) => {
  ctx.body = {
    name: "gt",
    age: 19,
    method: "post",
  };
});
/*
- 使用路由你还需要加上两句话
- 告诉它我要使用这个路由,告诉它我需要自动设置响应头
- router.routes()启动路由功能
- router.allowedMethods()自动设置响应头
 */
app.use(router.routes()).use(router.allowedMethods());
app.listen(999);

效果图