老莫的笔记本  
  
查看: 1307|回复: 0

KOA的路由

[复制链接]

662

主题

878

帖子

5145

积分

超级版主

Rank: 8Rank: 8

积分
5145
发表于 2018-5-8 10:32:37 | 显示全部楼层 |阅读模式
本帖最后由 周大胖子 于 2018-5-8 17:35 编辑

1.安装koa-router模块。
  1. npm install --save koa-router
复制代码
2.引入并实例化
  1. const Koa = require('koa');
  2. const Router = require('koa-router'); //引入路由
  3. const app = new Koa();
  4. const router = new Router(); // 实例化路由
  5. router.get('/',(ctx)=>{
  6.     ctx.body='哈哈哈哈 渣渣  这是首页'
  7. }).get('/news',(ctx)=>{
  8.     ctx.body='这尼玛是新闻列表页'
  9. })
  10. // get 传值
  11. // http://localhost:3000/news3?page=3&name=wang
  12. router.get('/news3',(ctx)=>{
  13.     ctx.body= ctx.query  // {"page":"3","name":"wang"}
  14.     console.log(ctx.query)  // {"page":"3","name":"wang"}
  15.     console.log(ctx.querystring)    //page=3&name=wang
  16. })
  17. // get 动态路由
  18. // http://localhost:3000/news2/ko2
  19. router.get('/news2/:aid',(ctx)=>{
  20.     ctx.body= ctx.params   //{"aid":"ko2"}
  21.     console.log( ctx.params ) //{"aid":"ko2"}
  22. })
  23. app.use(router.routes());  // 作用:启动路由
  24. app.use(router.allowedMethods()); // 作用:放在路由最后 根据 ctx.status 设置 response响应头
  25. app.listen(3000,()=>{
  26.     console.log('start at port 3000');
  27. })
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表