• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
smileyqp
https://github.com/smileyqp
博客园    首页    新随笔    联系   管理    订阅  订阅

【3、koa】koa路由

gitbook之koa路由

koa路由

npm install --save koa-router安装路由

var Koa = require('koa');
var app = new Koa();

//引入和实例化路由
var router = require('koa-router')();

//ctx是指上下文context;包含了request和response等信息
//配置路由
router.get('/',async(ctx)=>{
    ctx.body = 'hello';
})

router.get('/news',async(ctx)=>{
    ctx.body = 'news';
})

router.get('/details',async(ctx)=>{ 
    ctx.body = 'details';
})

//启动路由
app
    .use(router.routes())
    .use(router.allowedMethods())       
    //官方建议配置;因为这个是当没有设置享有的时候会根据ctx.status设置响应头


app.listen(3001)
//配置路由也可以这样写
router.get('/',async(ctx)=>{
    ctx.body = 'hello';
}).get('/news',async(ctx)=>{
    ctx.body = 'news';
})

获取get传值

在koa2中GET传值通过request接受,但是接受方法有两种:query和querystring
  • query:返回的是格式化好的参数对象
  • querystring:返回的是请求字符串
/**
 * 获取get传值
 * http://localhost:3001/details?aid=123
 */
router.get('/details',async(ctx)=>{
    console.log(ctx.query)      //{ aid: '123' }获取的是对象(推荐)
    console.log(ctx.querystring)    //aid=123   获取的是一个字符串
    console.log(ctx.request.query)      //同上获取query对象
    console.log(ctx.request.querystring)    //同上获取query的字符串

    console.log(ctx.request)    //获取请求相关信息

    //获取url地址
    console.log(ctx.url)
    console.log(ctx.request.url)
    
    ctx.body = 'details';
})

动态路由

/**
 * 动态路由
 * http://localhost:3001/news/23/90
 */
router.get('/news/:aid/:cid',async(ctx)=>{
    console.log(ctx.params) //获取动态路由的返回值{ aid: '23',cid:90 }
    ctx.body = 'news';
})
posted @ 2020-01-03 17:27  smileyqp  阅读(129)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3