KOA2
**定义:**Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。
1、async和await
async用于声明一个function是异步的,会返回一个Promise对象
await用于等待一个异步方法执行完成,可以获取异步方法里面的数据,但是必须得用在异步方法里面
2、Koa路由
定义:路由就是根据不同URL地址,加载不同的页面实现不同的功能,和express不同,express直接引入express就可以配置路由,在Koa中需要引入Koa-router路由模块来实现
案例
const Koa = require('koa')
const Router = require('koa-router')
//实例化koa
let app = new Koa()
let router = new Router()
//ctx(上下文context)包含了request和response等信息
router.get('/index',async (ctx)=>{
ctx.body = 'Hello,Wold'
})
//动态路由
router.get('/index/:aid',async (ctx)=>{
let params = ctx.params
if(params.aid == 'a'){
ctx.body = 'aaaaa'
}else{
ctx.body = 'bbbb'
}
})
app.use(router.routes()) //启动路由
.use(router.allowedMethods) //所有路由中间件调用后,会根据ctx.status设置response响应头
app.listen(3005)
3、获取get传值
get传值通过request接收,有两种方式:ctx.query和ctx.querystring
query:返回的是格式化好的参数对象 格式:{ name: ‘zs’, age: ‘12’ }
querystring:返回的是请求字符串 格式:name=zs&age=12
4、获取post请求参数
对于POST请求的处理,koa2没有封装获取参数的方法,需要通过解析上下文context中的原生node.js请求对象req,将POST表单数据解析成querystring(例如:a=1&b=2&c=3),再将querystring 解析成JSON格式(例如:{“a”:“1”, “b”:“2”, “c”:“3”)
对于POST请求的处理,使用koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中,通过ctx.request.body 获取post提交的数据
5、Koa中间件
**定义:**中间件就是匹配路由之前或者匹配路由完成做的一系列的操作,如果我的get、post回调函数中,没有next参数,那么就匹配上第一个路由,就不会往下匹配了。如果想往下匹配的话,那么需要写next()
中间件种类:
- 应用级中间件
- 路由级中间件
- 错误处理中间件
- 第三方中间件
1.应用级中间件
/**
* 在匹配路由之前都要打印日期(或者在匹配登录路由之前要进行权限判断)
*/
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(async (ctx,next)=>{
console.log(new Date());
await next();
})
router.get('/', function (ctx, next) {
ctx.body="Hello koa";
})
app.use(router.routes()); //作用:启动路由
app.use(router.allowedMethods()); //作用: 当请求出错时的处理逻辑
app.listen(3000,()=>{
console.log('starting at port 3000');
});
2、路由中间件
router.get('/', async(ctx, next)=>{
console.log(1)
next()
})
router.get('/', function (ctx) {
ctx.body="Hello koa";
})
3、错误处理中间件
app.use(async (ctx,next)=> {
next();
if(ctx.status==404){
ctx.status = 404;
ctx.body="这是一个404页面"
}
});
4、第三方中间件
const static = require('koa-static');
const staticPath = './static';
app.use(static(
path.join( __dirname, staticPath)
))
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
6、Koa中间件的执行顺序
Koa 选择了洋葱圈模型(从外到内,再从内到外执行)
案例
const Koa = require('koa')
const Router = require('koa-router')
//实例化koa
let app = new Koa()
let router = new Router()
app.use(async (ctx,next)=>{
console.log('1、这是第一个中间件');
await next()
console.log('5、匹配路由完成以后返回来执行中间件')
} )
app.use(async (ctx,next)=>{
console.log('2、这是第二个中间件');
await next()
console.log('4、匹配路由完成以后返回来执行中间件')
} )
router.get('/login',async (ctx)=>{
console.log('3、匹配到news路由')
ctx.body = '这是一个登录页面'
})
app.use(router.routes()) //启动路由
.use(router.allowedMethods) //所有路由中间件调用后,会根据ctx.status设置response响应头
app.listen(3005)
执行结果
1、这是第一个中间件
2、这是第二个中间件
3、匹配到news路由
4、匹配路由完成以后返回来执行中间件
5、匹配路由完成以后返回来执行中间件
7、Koa2中 Cookie的使用
1、Koa中设置Cookie的值
ctx.cookies.set(name, value, [options])
options 名称 options 值
maxAge 多少毫秒数过期
expires 过期的 Date
path 路径, 默认是'/'
domain 域名
secure 安全 cookie 默认false,设置成true表示只有 https可以访问
httpOnly 是否只是服务器可访问 cookie, 默认是 true
2、Koa中获取Cookie的值
ctx.cookies.get('name');
3、Koa中无法直接设置中文的cookie,可以用buffer解决
console.log(new Buffer('张三').toString('base64'));// 转换成base64字符串:aGVsbG8sIHdvcmxkIQ==
console.log(new Buffer('aGVsbG8sIHdvcmxkIQ==', 'base64').toString());// 还原base64字符串:张三
8、Koa2中 Session的使用
配置session
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa:sess', //cookie key (default is koa:sess)
maxAge: 86400000, // cookie的过期时间 maxAge in ms (default is 1 days)
overwrite: true, //是否可以overwrite (默认default true)
httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
signed: true, //签名默认true
rolling: false, //在每次请求时强行设置cookie,这将重置cookie过期时间(默认:false)
renew: false, //(boolean) renew session when session is nearly expired,
};
app.use(session(CONFIG, app));
使用
设置值 ctx.session.username = "张三";
获取值 ctx.session.username
9、Koa中使用art-template模板引擎
1.安装art-template 和 koa-art-template
npm install --save art-template
npm install --save koa-art-template
2.配置Koa2中间件:
const Koa = require('koa');
const render = require('koa-art-template');
const app = new Koa();
render(app, {
root: path.join(__dirname, 'view'),
extname: '.html',
debug: process.env.NODE_ENV !== 'production'
});
//渲染index.html
app.use(async function (ctx) {
await ctx.render('index');
});
app.listen(8001);
art-template模板引擎语法
绑定数据: {{list.name}} 条件: {{if num>20}}大于20{{else}}小于20{{/if}} 循环数据: {{each list.data}} {{$index}}---{{$value}} {{/each}} 引入模板: {{include 'public/footer.html'}}
10、Koa中使用ejs模板引擎
1、安装 koa-views 和ejs
1.安装koa-views npm install --save koa-views
2.安装ejs npm install ejs --save
2、引入koa-views配置中间件
const views = require('koa-views');
app.use(views('views', { map: {html: 'ejs' }}));
3、Koa中使用ejs:
router.get('/add',async (ctx)=>{
let title = 'hello koa2'
await ctx.render(index',{
title
})
})
4、ejs语法
Ejs引入模板: <%- include header.ejs %>
Ejs绑定数据: <%=h%>
Ejs绑定html数据: <%-h%>
Ejs模板判断语句: <% if(true){ %>
true
<%} else{ %>
false
<%} %>
Ejs模板中循环数据 : <%for(var i=0;i<list.length;i++){%>
<%=list[i] %>
<%}%>