koa学习文档
安装
nosejs版本>7.6
npm init --yes //强制生成
npm install --save koa
helloword 世界你好
var koa = require('koa');
var app = new koa();
// 配置路由
app.use(async(ctx)=>{
ctx.body='helloword'
})
app.listen(3000);
koa路由
由一个URL和一个特定http方法组成
即路由就是根据不同URL地址,加载不同的页面实现不同的功能。
koa需要安装对应koa-router路由模块实现
npm install --save koa-router
// 引入koa模块
var Koa = require('koa');
var Router = require('koa-router');
// 实例化
var app = new Koa();
var router = new Router();
// 配置路由
// ctx 上下文 context,包含了request和responese等信息
router.get('/',async (ctx,next)=>{
ctx.body='首页' //返回数据 类似res.send
}).get('/news',async(ctx)=>{
ctx.body='新闻页面'
})
app
.use(router.routes()) //启动路由
.use(router.allowedMethods()); //设置对应响应头可选
app.listen(3000);
路由传值
get传值
koa中get传值通过request接收,两种:query和querystring
query:返回是格式化好的参数对象
querystring:返回的是请求字符传
// 从ctx中读取get传值
console.log(ctx.query);//⭐⭐⭐[Object: null prototype] { aid: '123', name: 'lisi' }
console.log(ctx.querystring);//aid=123&name=lisi
// ctx里面的request里面获取get传值
console.log(ctx.request);
//{
// method: 'GET',
// url: '/news?aid=123&name=lisi',
// header: {
// host: 'localhost:3000',
// connection: 'keep-alive',
// 'cache-control': 'max-age=0',
// 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
// 'sec-ch-ua-mobile': '?0',
// 'upgrade-insecure-requests': '1',
// 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36',
// accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed- exchange;v=b3;q=0.9',
// 'sec-fetch-site': 'none',
// 'sec-fetch-mode': 'navigate',
// 'sec-fetch-user': '?1',
// 'sec-fetch-dest': 'document',
// 'accept-encoding': 'gzip, deflate, br',
// 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ko;q=0.6,ja;q=0.5',
// cookie: 'authorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im5haW5haSIsImlhdCI6MTYyNzAzMzI4MSwiZXhwIjoxNjI3MTE5NjgxfQ.GASP8JvQNlKa1VC07an1mDIlhs7eoLn4lV16-ZfW-aE; sidebarStatus=0'
// }
// }
console.log(ctx.request.query);//[Object: null prototype] { aid: '123', name: 'lisi' }
console.log(ctx.request.querystring);//aid=123&name=lisi
动态路由
router.get('/news/:aid',async(ctx)=>{
// 获取动态路由传值
// http://localhost:3000/news/ww
console.log(ctx.params);//{ aid: 'ww' }
ctx.body='新闻页面'
})
后台控制路由跳转
跳转到views下index.ejs页面
koa中间件
匹配路由之前或者匹配路由完成做的一系列的操作
和express中间件相似,是一个函数,可以访问请求对象,响应对象,和web应用中处理请求-响应循环流程中的中间件,一般被命名为next的变量。
功能包括:
- 执行任何代码
- 修改请求和响应对象
- 终结请求-响应循环
- 调用堆栈中的下一个中间件
get和post回调函数中,没有next参数,那么匹配上第一个路由,就不会往下匹配。如果往下匹配,需要写next()
koa可使用几种中间件
执行顺序如洋葱
koa2中间件是基于async/await实现的,其执行过程是通过next来驱动的
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
console.log('第一层洋葱 - 开始')
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${
ctx.method} ${
ctx.url} - ${
rt}`);
console.log('第一层洋葱 - 结束')
});
// x-response-time
app.use(async (ctx, next) => {
console.log('第二层洋葱 - 开始')
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${
ms}ms`);
console.log('第二层洋葱 - 结束')
});
// response
app.use(async ctx => {
console.log('第三层洋葱 - 开始')
ctx.body = 'Hello World';
console.log('第三层洋葱 - 结束')
});
app.listen(8000);
打印结果
第一层洋葱 - 开始
第二层洋葱 - 开始
第三层洋葱 - 开始
第三层洋葱 - 结束
第二层洋葱 - 结束
第一层洋葱 - 结束
应用级中间件
// 匹配任何路由处理
app.use(async (ctx)=>{
ctx.body='中间件'
})
app.use(async (ctx,next)=>{
console