KOA笔记

KOA相关笔记

全局安装

npm i koa-generator -g

创建项目

koa koa_demo

重要包

koa-router

koa-bodyparser

koa-jwt

1
2
3
4
5
6
7
8
9
// hello world
const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
ctx.body = 'Hello World';
});

app.listen(3000);

应用级中间件

app.

next

1
2
3
4
//next匹配到路由以后继续向下
router.get('/news',async(ctx,net)=>{
await next();
})

路由级中间件

1
2
//引入和实例化路由
const router = require('koa-router')();
1
2
3
4
5
6
7
8
9

//路由配置表
const user = require('./user');
const letter = require('./letter');
module.exports = function(app){
//启动路由
app.use(user.routes()).use(user.allowedMethods());
app.use(letter.routes()).use(letter.allowedMethods());
}

KOA中间件执行流程

洋葱

错误处理中间件

1
2
3
4
5
6
7
app.use(async(ctx,next)=>{
next();
if(ctx.status===404){
ctx.status=404
ctx.body="404"; //重定向404
}
})

第三方中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//koa-static
const static = require('koa-static');
const staticPath = './static';
app.use(static(
path.join(__dirname,staticPath)
))

// koa-bodyparser
const bodyParser=require('koa-bodyparser');
app.use(bodyParser());
app.use(async ctx => {
// the parsed body will store in ctx.request.body
// if nothing was parsed, body will be an empty object {}
ctx.body = ctx.request.body;
});

模板

ejs
art-template

1
2
3
4
5
6
ctx.cookies.set('token','123',{
maxAge:3600,
path:'/news',//配置可以访问的路径
httpOnly:true, //true只有服务器可以访问 false表示客户端都可以访问
domain:'' //域名默认当前域 .baidu.com 子域可以共享cookies数据
})