安装koa和koa-router
代码语言:javascript复制npm install koa --save
npm install koa-router --save
代码语言:javascript复制var koa = require('koa');
var Router = require('koa-router');
var app = new koa();
var router = new Router();
router.get('/', async (ctx) => {
ctx.body = "首页";
})
router..get('/news', async (ctx) => {
ctx.body = "新闻";
})
// 获取get传值
router.get('/newsContent', async (ctx) => {
// http://localhost:3000/newsContent?id=3
console.log(ctx.query.id) //获取get传值 3
ctx.body = "新闻详情";
})
// 配置动态路由
router.get('/newsCtx/:id', async (ctx) => {
// http://localhost:3000/newsCtx/koa
console.log(ctx.params) //获取动态路由返回值
ctx.body = "新闻详情";
})
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000);