|
本帖最后由 周大胖子 于 2018-5-8 17:35 编辑
1.安装koa-router模块。- npm install --save koa-router
复制代码 2.引入并实例化- const Koa = require('koa');
- const Router = require('koa-router'); //引入路由
- const app = new Koa();
- const router = new Router(); // 实例化路由
- router.get('/',(ctx)=>{
- ctx.body='哈哈哈哈 渣渣 这是首页'
- }).get('/news',(ctx)=>{
- ctx.body='这尼玛是新闻列表页'
- })
- // get 传值
- // http://localhost:3000/news3?page=3&name=wang
- router.get('/news3',(ctx)=>{
- ctx.body= ctx.query // {"page":"3","name":"wang"}
- console.log(ctx.query) // {"page":"3","name":"wang"}
- console.log(ctx.querystring) //page=3&name=wang
- })
- // get 动态路由
- // http://localhost:3000/news2/ko2
- router.get('/news2/:aid',(ctx)=>{
- ctx.body= ctx.params //{"aid":"ko2"}
- console.log( ctx.params ) //{"aid":"ko2"}
- })
- app.use(router.routes()); // 作用:启动路由
- app.use(router.allowedMethods()); // 作用:放在路由最后 根据 ctx.status 设置 response响应头
- app.listen(3000,()=>{
- console.log('start at port 3000');
- })
复制代码
|
|