koa
路由
基本使用
不同于express,koa需要安装对应的koa-router路由模块:npm i koa-router
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const koa = require('koa'); const router = require('koa-router')();
const app = new Koa();
router .get('/', async (ctx, next) => { ctx.body = "首页"; }) .get('/news', async (ctx, next) => { ctx.body = "新闻"; })
app.use(router.routes()); app.use(router.allowedMethods());
app.listen(3000, () => { console.log('Server is running at 127.0.0.1:3000'); })
|
get传值
三种常用方式:
例:当url为:127.0.0.1:3000/?a=5&b=7
时,三者的值分别为:
{ a: '5', b: '7' }
a=5&b=7
/?a=5&b=7
动态路由
获取动态路由的传值:
1 2 3 4 5 6 7 8 9 10 11 12
| router.get('/news/:aid', async (ctx) => { console.log(ctx.query); console.log(ctx.params); ctx.body = "新闻"; })
router.get('/news/:aid/:cid', async (ctx) => { console.log(ctx.query); console.log(ctx.params); ctx.body = "新闻"; })
|
例:当url为http://127.0.0.1:3000/news/a?c=7
和http://127.0.0.1:3000/news/a/b?d=8
时,结果如注释
中间件
应用级中间件
匹配路由前进行一系列操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
app.use(async (ctx, next) => { console.log(new Date()); await next(); })
router .get('/', async (ctx, next) => { ctx.body = "首页"; }) .get('/news', async (ctx, next) => { ctx.body = "新闻"; })
|
不同于express的顺序执行,无论app.use是放在router.get/post前边还是后边,都会优先执行
路由级中间件
匹配到一个路由后,继续向下匹配:
1 2 3 4 5 6 7 8 9 10 11 12
| router .get('/', async (ctx, next) => { ctx.body = "首页"; }) .get('/news', async (ctx, next) => { console.log('新闻'); await next(); }) .get('/news', async (ctx, next) => { ctx.body = "新闻"; })
|
错误处理中间件
先进入app.use,进入next(),匹配结束后,再回到next()下边这一行,如果匹配成功则什么也不做,匹配失败就显示404
1 2 3 4 5 6
| app.use(async (ctx, next) => { await next(); if(ctx.status === 404){ ctx.body = "404 Not Found!" } })
|
第三方中间件
此处略,可以参考下方内容
配置模板引擎
- 安装koa-views和ejs:
npm i koa-views
,npm i ejs
- 引入koa-views配置中间件
- Koa中使用ejs
app.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const views = require('koa-views'); const app = new Koa();
app.use(views('views', {extension: 'ejs'}));
router .get('/', async (ctx, next) => { let arr = ['张三', '李四', '王五']; await ctx.render('index', { arr }) })
app.use(router.routes()); app.use(router.allowedMethods());
app.listen(3000, () => { console.log('Server is running at 127.0.0.1:3000'); })
|
index.ejs:
1 2 3 4 5 6
| <p>这是一个ejs的模板引擎</p> <ul> <% for(let i = 0; i < arr.length; i++) { %> <li><%= arr[i] %></li> <% } %> </ul>
|
post提交数据
- 安装:
npm i koa-bodyparser
- 引入
- app.use配置中间件
- 用ctx.request.body获取表单提交的数据
静态资源