Koa——新的web框架
Koa是一个新的web框架,由Express幕后的原班人马打造,致力于成为web应用和API开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用async函数,Koa丢弃回调函数,并有力地增强错误处理。Koa并没有捆绑任何中间件,而是提供了一套优雅的方法。
官网:https://koajs.com/,GitHub 仓库:https://github.com/koajs/koa,翻译的中文网:https://koa.bootcss.com/,基于Node.js平台新的web框架,是下一代web开发框架。
Koa使用洋葱模型
洋葱模型,一层包裹一层,nodejs框架的执行就像是中间穿过洋葱的一条线,而每一层洋葱皮就代表一个中间件,进入时穿过多少层,出来时还得穿出多少层,具有先进后出(栈)的特点。
koa洋葱圈模型:1、中间件机制,是koa2的精髓;2、每个中间件都是async函数;3、中间件的运行机制,就像洋葱圈。
Koa的上下文(Context)
Koa Context,node的request和response对象封装到单个对象中,为编写Web应用程序和API提供了许多有用的方法,这些操作在HTTP服务器开发中频繁使用,被添加到此级别而不是更高级别的框架,这将强制中间件重新实现这些通用功能。
Koa框架路由
const router = require('koa-router')();,require("koa-router") 返回的是函数,执行之后返回对象。
案例代码
安装命令
npm init -y
npm install koa --save
npm install koa-router --save
npm install koa-bodyparser --save-dev
使用版本:
{
"name": "koa01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.13.4",
"koa-router": "^10.1.1"
},
"devDependencies": {
"koa-bodyparser": "^4.3.0"
}
}
案例一:
const Koa = require('koa');
const app = new Koa();
// 日志
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// 响应(访问所有地址,处理相同)
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
console.log('app started at port 3000...');
案例二,执行顺序:
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(function* (next) {
// (1) 进入路由
console.log(1, "进入路由");
const start = new Date;
yield next;
// (5) 再次进入 x-response-time 中间件,记录2次通过此中间件「穿越」的时间
console.log(5, "再次进入 x-response-time 中间件");
const ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
// (6) 返回 this.body
console.log(6, "返回 this.body");
});
// logger
app.use(function* (next) {
// (2) 进入 logger 中间件
console.log(2, "进入 logger 中间件");
const start = new Date;
yield next;
// (4) 再次进入 logger 中间件,记录2次通过此中间件「穿越」的时间
console.log(4, "再次进入 logger 中间件");
const ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
// response
app.use(function* () {
// (3) 进入 response 中间件,没有捕获到下一个符合条件的中间件,传递到 upstream
console.log(3, "进入 response 中间件");
this.body = 'Hello World~';
});
app.listen(3000);
案例三,路由及GET、POST:
const BodyParser = require('koa-bodyparser');
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const bodyparser = new BodyParser();
app.use(async (ctx, next) => {
console.log(`Process 请求方式:${ctx.request.method},请求URL:${ctx.request.url}...`);
await next();
});
// middleware的顺序
app.use(bodyparser);
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
ctx.response.body = ctx.response.body + "<p>" + ms + "ms</p>";
});
// http://127.0.0.1:3000/main/%E4%BD%A0%E5%A5%BD
router.get('/main/:name', async (ctx, next) => {
let name = ctx.params.name;
ctx.response.body = `<h1>main, ${name}!</h1>`;
});
// http://127.0.0.1:3000/user?id=100001&name=李四
// koa-router url get传值
router.get("/user", async (ctx, next) => {
//get传值
console.log(ctx.request.query);
ctx.response.body = "获取get传值=>" + JSON.stringify(ctx.request.query);
});
// http://127.0.0.1:3000/regest
//get路由
router.get("/regest", async (ctx, next) => {
ctx.response.body = `
<form action='/regest' method='post'>
<input type='text' name='id'/>
<button>注册</button>
</form>
`;
});
// post
router.post('/regest', async (ctx, next) => {
console.log(ctx.request.body);
ctx.response.body = "注册成功=>" + JSON.stringify(ctx.request.body);
})
// http://127.0.0.1:3000/
router.get('/', async (ctx, next) => {
ctx.response.body = '<h1>我是首页!</h1>';
});
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');