Koa路由、get传值、动态路由

Koa路由、get传值、动态路由

十二月 09, 2018

一、Koa路由

路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等)组成的,应用涉及到如何响应客户端对某个网站节点的访问。通俗的讲:路由就是根据不同的 URL 地址,加载不同的页面,实现不同的功能。
Koa 中的路由和 Express 有所不同,在 Express 中直接引入 Express 就可以配置路由,但是在 Koa 中我们需要安装对应的 koa-router 路由模块来实现。

1
npm install --save koa-router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const Koa = require('koa');
const router = require('koa-router')(); //注意引入的方式

const app = new Koa()

router.get('/',async (ctx)=>{ //context上下文,包含了req与res

ctx.body="首页" //相当于原生里面的res.writeHead() 和 res.end()
})

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

ctx.body="新闻"
});
app.use(router.routes()) //启动路由
app.use(router.allowedMethods()) //在所有路由中间件中最后调用
app.listen(3000)

二、Koa 路由 get 传值

在 Koa 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。
1、query:返回的是格式化好的参数对象
2、querystring:返回的是请求字符串

1
2
3
4
5
6
7
8
9
router.get('/newscontent',(ctx,next)=>{

//从ctx中读取get传值
console.log(ctx.query) //{ aid: '123' },获取的是对象。用的最多的方式
console.log(ctx.querystring) //aid=123&name=zhangsan,获取的是一个字符串
console.log(ctx.url) //获取url地址

ctx.body="新闻详情";
});

三、Koa 动态路由

动态路由传值的获取方法:http://域名/newscontent/xxxx

1
2
3
4
5
6
router.get('/newscontent/:aid',async (ctx)=>{

console.log(ctx.params); //{ aid: 'xxxx' }

ctx.body="新闻详情";
})

动态路由里面可以传入多个值 /newscontent/:aid/:cid