浏览器调用
http://localhost:3000/?aid=00
运行项目控制台查看
// 引入koa和路由模块
let Koa = require('koa');
let router = require('koa-router')();
// 实例化
let app = new Koa();
router.get('/', async (ctx, next) => {
ctx.body = "首页";
/**
* 在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。
* query:返回的是格式化好的参数对象。
* querystring:返回的是请求字符串。
*/
// 从ctx读取get传值
console.log(ctx);
console.log(ctx.query);
console.log(ctx.querystring);
console.log(ctx.url);
// ctx里面的request里面获取get传值
console.log(ctx.request);
console.log(ctx.request.query);
console.log(ctx.request.querystring);
console.log(ctx.request.url);
})
router.get('/news', async (ctx, next) => {
ctx.body = "新闻";
});
// 动态路由传递一个值
router.get('/newsDetail/:id', async (ctx, next) => {
ctx.body = '新闻详情';
// 获取动态路由的传值 http://localhost:3000/newsDetail/002
console.log(ctx.params); // { id: '002' }
});
// 动态路由传递多个值
router.get('/product/:id/:name', async (ctx, next) => {
ctx.body = '产品';
// 获取动态路由的传值 http://localhost:3000/product/002/衣服
console.log(ctx.params); // { id: '002', name: '衣服' }
});
app
.use(router.routes())
.use(router.allowedMethods());
// 监听端口
app.listen(3000);