路由:
路由是由一个url(路径)以及一个特定的http方法组合成的,,涉及响应客户端对于某个网站的访问
通俗的讲就是 依据不同的url地址展示不同的网站内容。
区别于express的路由,koa需要进行导入路由模块。
get传值
koa2中的get传值通过request接受,但是接受的方式有两种:query、querystring。
- query:已经格式化好的对象
- querystring:原始的参数字符串。
动态路由
在某一个路由的基础上绑定动态路由后续的路由参数可以用以数据库的查询。
let Koa = require('koa');
let router = require('koa-router')();
//引入实例化路由
let app = new Koa();
//配置路由
router.get('/',async ctx => {
ctx.body = '首页'//相当于write返回数据
}).get('/new',async ctx => {
ctx.body = '新闻'
/*ctx获取get参数值用的最多*/
console.log(ctx.query) /*{ a: '2', b: '44' }*/
console.log(ctx.querystring)/*a=2&b=44*/
/*ctx中的request中获取*/
console.log(ctx);
}).get('/content/:id/:name',async ctx => {
/*获取动态路由传值,可以接受多个值*/
/*http://localhost:3003/content/ddd */
console.log(ctx.params);
/*{ id: 'ddd', name: 'xxx' }*/
ctx.body = 'this is content'
})
app.use(router.routes()) //启动路由
.use(router.allowedMethods())//给路由添加响应头
app.listen(3003)