KOA框架
优点:它的特点是优雅、简洁、表达力强、自由度高,ES6语法支持很多,同步模式也很到位,利用生成器函数(Generator Function)来作为响应器,不需要回调函数。
缺点:分层不太明显,大部分功能需要通过插件完成, Connect/Express 的中间件基本不能重用。
初始化package.json
$ npm init
安装koa:
$ npm install koa
安装完成后会得到以下3个文件:
KOA的核心文件:
- application.js
application.js是koa的入口文件,它向外导出了创建class实例的构造函数,它继承了events,这样就会赋予框架事件监听和事件触发的能力。application还暴露了一些常用的api,比如toJSON、listen、use等等;
listen的实现原理其实就是对http.createServer进行了一个封装,重点是这个函数中传入的callback,它里面包含了中间件的合并,上下文的处理,对res的特殊处理;
use是收集中间件,将多个中间件放入一个缓存队列中,然后通过koa-compose这个插件进行递归组合调用这一些列的中间件。
-
context.js
这部分就是koa的应用上下文ctx,其实就一个简单的对象暴露,里面的重点在delegate,这个就是代理,这个就是为了开发者方便而设计的,比如我们要访问ctx.repsponse.status但是我们通过delegate,可以直接访问ctx.status访问到它。
- request.js 、response.js
这两部分就是对原生的res、req的一些操作了,大量使用es6的get和set的一些语法,去取headers或者设置headers、还有设置body等等,这些就不详细介绍了,有兴趣的读者可以自行看源码。
一、基本用法
1.1.使用Koa 架设一个 HTTP 服务
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
1.2.HTTP Response 的类型
Koa 默认的返回类型是text/plain
(纯文本的形式),如果想返回其他类型的内容,可以先用ctx.request.accepts
判断一下,客户端希望接受什么数据(根据 HTTP Request 的Accept
字段),然后使用ctx.response.type
指定返回类型。
const Koa = require('koa')
const app = new Koa()
//声明一个main中间件,如果你急于了解中间件可以跳转到(三)
const main = (ctx,next) =>{
if (ctx.request.accepts('json')) {
ctx.response.type = 'json';
ctx.response.body = { data: 'Hello World' };
} else if (ctx.request.accepts('html')) {
ctx.response.type = 'html';
ctx.response.body = '<p>Hello World</p>';
} else if (ctx.request.accepts('xml')) {
ctx.response.type = 'xml';
ctx.response.body = '<data>Hello World</data>';
} else{
ctx.response.type = 'text';
ctx.response.body = 'Hello World';
};
}; //直接运行页面中会显示json格式,因为我们没有设置请求头,所以每一种格式都是ok的。
app.use(main)//app.use()用来加载中间件。
app.listen(3000)
1.3.网页模板
app.js
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./data/index.html');
};
app.use(main);
app.listen(3000);
index.html(目录:./data/)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>我的第一个网页</title>
</head>
<body>
<h1>我的第一个网页标题</h1>
<p>我的第一个段落。</p>
<p><font color="blue">我的第一个网页,蓝色文字。</font></p>
</body>
</html>
二、路由
2.1.原生路由
const Koa = require('koa')
const app = new Koa()
app.use((ctx, next) => {
if (ctx.request.url == '/') {//通过ctx.request.url获取用户请求路径
ctx.body = '<h1>首页</h1>'
} else if (ctx.request.url == '/my') {
ctx.body = '<h1>联系我们</h1>'
} else {
ctx.body = '<h1>404 not found</h1>'
}
})
app.listen(3000)
分别访问127.0.0.1:3000 127.0.0.1:3000/my 127.0.0.1:3000/1
2.2. koa-router 模块路由
$ npm install koa-router
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
app.use(router.routes()).use(router.allowedMethods());
//routes()返回路由器中间件,它调度与请求匹配的路由。
//allowedMethods()处理的业务是当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.
router.get('/',(ctx,next)=>{//.get就是发送的get请求
ctx.response.body = '<h1>koa-router 模块路由测试-首页</h1>'
})
router.get('/my',(ctx,next)=>{
ctx.response.body = '<h1>koa-router 模块路由测试-联系我们</h1>'
})
app.listen(3000)
2.3.静态资源
如果网站提供静态资源(图片、字体、样式表、脚本......),为它们一个个写路由就很麻烦,也没必要koa-static模块封装了这部分的请求。请看下面的例子
$ npm install koa-staic
app.js
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname));
app.use(main);
app.listen(3000);
index.html(./data/)
2.4.重定向跳转
有些场合,服务器需要重定向访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()
方法可以发出一个跳转,将用户导向另一个路由。
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router()
app.use(router.routes()).use(router.allowedMethods());
router.get('/cdx',(ctx,next)=>{
ctx.response.redirect('/');//发出一个跳转,将用户导向另一个路由。
})
router.get('/',(ctx,next)=>{
ctx.response.body = '<h1>koa-router 模块路由测试-重定向-首页</h1>'
})
app.listen(3000);
访问 127.0.0.1:3000/ctx 会跳转到 127.0.0.1:3000
三、中间件
3.1.Logger功能
Koa 的最大特色,就是中间件。为了理解中间件,我们先看一下 Logger (打印日志)功能的实现。
logger.js
const Koa = require('koa')
const koaLogger = require('./logger/koa-logger')
const app = new Koa();
app.use(koaLogger)
app.listen(3000)
koa-logger.js
module.exports = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);//自定义
}
打印结果:
3.2.中间件
处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能的函数,就叫做"中间件"。
基本上,Koa 所有的功能都是通过中间件实现的, 每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是next
函数。只要调用next
函数,就可以把执行权转交给下一个中间件。
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next)=>{
console.log('>> one');
next(); //调用next函数,把执行权交给下一个中间件。
})
app.use((ctx, next)=>{
console.log('>> two');
next(); //调用next函数,把执行权交给下一个中间件。注释之后,下一个中间件函数就不会执行
})
app.use((ctx, next)=>{
console.log('>> three');
next(); //调用next函数,把执行权交给下一个中间件。
})
app.use(ctx=>{
console.log('>> 准备响应');
ctx.body='hello';
})
app.listen(3000);
多个中间件会形成一个栈结构,以"先进后出"的顺序执行。
- 最外层的中间件首先执行。
- 调用
next
函数,把执行权交给下一个中间件。 - ...
- 最内层的中间件最后执行。
- 执行结束后,把执行权交回上一层的中间件。
- ...
- 最外层的中间件收回执行权之后,执行
next
函数后面的代码。
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next)=>{
console.log('>> one');
next(); //调用next函数,把执行权交给下一个中间件。
console.log('<< one');//最外层的中间件收回执行权之后,执行next函数后面的代码。
})
app.use((ctx, next)=>{
console.log('>> two');
next(); //调用next函数,把执行权交给下一个中间件。
console.log('<< two');
})
app.use((ctx, next)=>{
console.log('>> three');
next();
console.log('<< three');
})
app.listen(3000);
3.3.异步中间件
迄今为止,所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成async 函数。
$ npm install fs.promised
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./data/index.html', 'utf8');
};
app.use(main);
app.listen(3000);
上面代码中,fs.readFile
是一个异步操作,必须写成await fs.readFile()
,然后中间件必须写成 async 函数。
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
function delay(){
return new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove()
},2000)
})
}
app.use(async(ctx, next)=>{
ctx.body = '1'
await next()
ctx.body += '2'
})
app.use(async(ctx, next)=>{
ctx.body += '3'
await delay()
await next()
ctx.body += '4'
})
app.listen(3000);
访问127.0.0.1:3000 延时2秒后跳出页面:
3.4.中间件的合成
koa-compose 模块可以将多个中间件合成一个
$ npm install koa-compose
const Koa = require('koa');
const compose = require('koa-compose');
const app = new Koa();
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
const main = ctx => {
ctx.response.body = 'Hello World';
};
const middlewares = compose([logger, main]);//合成中间件
app.use(middlewares);//加载中间件
app.listen(3000);
输出结果:先打印日志,再在页面中显示Hello World
四、处理错误
4.1. 500错误
如果代码运行过程中发生错误,我们需要把错误信息返回给用户。HTTP 协定约定这时要返回500状态码。Koa 提供了ctx.throw()
方法,用来抛出错误,ctx.throw(500)
就是抛出500错误。
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.throw(500);//这个时候你访问首页会报一个500的错误(内部服务器错误)服务器会报错
};
app.use(main);
app.listen(3000);
4.2. 404错误
如果将ctx.response.status
设置成404,就相当于ctx.throw(404)
,返回404错误。
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.status = 404;//response返回的状态码就是404
ctx.response.body = 'Page Not Found';//让页面中显示该内容,服务器不不报错
};
app.use(main);
app.listen(3000);
4.3 处理错误的中间件
为了方便处理错误,最好使用try...catch
将其捕获。但是,为每个中间件都写try...catch
太麻烦,我们可以让最外层的中间件,负责所有中间件的错误处理。
const Koa = require('koa');
const app = new Koa();
const handler = async (ctx, next) => {
try {
await next();//执行下个中间件
} catch (err) {
//如果main中间件是有问题的会走这里
ctx.response.status = err.statusCode || err.status || 500;
ctx.response.body = {
message: err.message//把错误信息返回到页面
};
}
};
const main = ctx => {
ctx.throw(500);//如果这里是没有问题的就正常执行,如果有问题会走catach
};
app.use(handler);
app.use(main);
app.listen(3000);
4.4 errors事件监听
运行过程中一旦出错,Koa 会触发一个error
事件。监听这个事件,也可以处理错误。
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.throw(500);
};
app.on('error', (err, ctx) => {
//如果有报错的话会走这里
console.error('server error', err);//err是错误源头
});
app.use(main);
app.listen(3000);
4.5 释放error事件
需要注意的是,如果错误被try...catch
捕获,就不会触发error
事件。这时,必须调用ctx.app.emit()
,手动释放error
事件,才能让监听函数生效。
const Koa = require('koa');
const app = new Koa();
const handler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.response.status = err.statusCode || err.status || 500;
ctx.response.type = 'html';
ctx.response.body = '<p>有问题,请与管理员联系</p>';
ctx.app.emit('error', err, ctx);//释放error事件
}
};
const main = ctx => {
ctx.throw(500);
};
app.on('error', function (err) {
//释放error事件后这里的监听函数才可生效
console.log('错误', err.message);
console.log(err);
});
app.use(handler);
app.use(main);
app.listen(3000);
上面代码main
函数抛出错误,被handler
函数捕获。catch
代码块里面使用ctx.app.emit()
手动释放error
事件,才能让监听函数监听到。
五、Web App的功能
5.1 cookie
ctx.cookies
用来读写 Cookie。
const Koa = require('koa');
const app = new Koa();
const main = function(ctx) {
//读取cookie//没有返回0
const n = Number(ctx.cookies.get('view') || 0) + 1;
ctx.cookies.set('view', n);//设置cookie
ctx.response.body = n + ' views';//显示cookie
}
app.use(main);
app.listen(3000);
开发中制作登录和保存用户信息在本地,最常用的就是cookie操作。比如我们在作一个登录功能时,希望用户在接下来的一周内都不需要重新登录就可以访问资源,这时候就需要我们操作cookie来完成我们的需求。koa的上下文(ctx)直接提供了读取和写入的方法。
- ctx.cookies.get(name,[optins]):读取上下文请求中的cookie。
- ctx.cookies.set(name,value,[options]):在上下文中写入cookie。
原文链接:https://www.jianshu.com/p/0457e4b038a9
写入Cookie操作:
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
if(ctx.url=== '/index'){
ctx.cookies.set(
'MyName','JSPang'
);
ctx.body = 'cookie is ok';
}else{
ctx.body = 'hello world'
}
});
app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
})
好后预览,打开F12可以在Application中找到Cookies选项。就可以找到我们写入的name和value了。
Cookie选项
比如我们要存储用户名,保留用户登录状态时,你可以选择7天内不用登录,也可以选择30天内不用登录。这就需要在写入是配置一些选项:
- domain:写入cookie所在的域名
- path:写入cookie所在的路径
- maxAge:Cookie最大有效时长
- expires:cookie失效时间
- httpOnly:是否只用http请求中获得
- overwirte:是否允许重写
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
if(ctx.url=== '/index'){
ctx.cookies.set(
'MyName','JSPang',{
domain:'127.0.0.1', // 写cookie所在的域名
path:'/index', // 写cookie所在的路径
maxAge:1000*60*60*24, // cookie有效时长
expires:new Date('2018-12-31'), // cookie失效时间
httpOnly:false, // 是否只用于http请求中获取
overwrite:false // 是否允许重写
}
);
ctx.body = 'cookie is ok';
}else{
ctx.body = 'hello world'
}
});
app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
})
读取Cookie:
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
if(ctx.url=== '/index'){
ctx.cookies.set(
'MyName','JSPang',{
domain:'127.0.0.1', // 写cookie所在的域名
path:'/index', // 写cookie所在的路径
maxAge:1000*60*60*24, // cookie有效时长
expires:new Date('2020-12-31'), // cookie失效时间
httpOnly:false, // 是否只用于http请求中获取
overwrite:false // 是否允许重写
}
);
ctx.body = 'cookie is ok';
}else{
if( ctx.cookies.get('MyName')){
ctx.body = ctx.cookies.get('MyName');
}else{
ctx.body = 'Cookie is none';
}
}
});
app.listen(3000,()=>{
console.log('[demo] server is starting at port 3000');
})
5.2 表单
Web 应用离不开处理表单。本质上,表单就是 POST 方法发送到服务器的键值对。koa-body模块可以用来从 POST 请求的数据体里面提取键值对。
$ npm install koa-body
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
const main = async function (ctx) {
const body = ctx.request.body;
if (!body.name){
ctx.throw(400, '.name required')
};
ctx.body = { name: body.name };
};
app.use(koaBody());
app.use(main);
app.listen(3000);
5.3 文件上传
koa-body模块还可以用来处理文件上传。
app.js
const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('koa-router');
const fs = require('fs');
const path = require('path');
const router = new Router()
const app = new Koa();
//配置中间件
app.use(koaBody({
multipart: true,//解析多部分主体,默认false
formidable: {
maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M
}
}));
app.use(router.routes()).use(router.allowedMethods());
router.post('/uploadfile', (ctx, next) => {
// 上传单个文件
const file = ctx.request.files.file; // 获取上传文件
//创建可读取流。这里要引入文件操作模块跳到index.js最上面,也就是本文件的头部,加上 const fs = require(‘fs’)
const reader = fs.createReadStream(file.path);
//创建一个文件,将一会我们要用的可写流写到这个这个目录的这个文件
let filePath = path.join(__dirname, 'data/') + `/${file.name}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
return ctx.body = "上传成功!";
});
const main = ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./index.html');
};
app.use(main);
app.listen(3000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="http://127.0.0.1:3000/uploadfile" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" multiple="multiple" />
<input type="submit" value="提交"/>
</form>
</body>
</html>
上传多个文件:
router.post('/uploadfile', async (ctx, next) => {
// 上传多个文件
const files = ctx.request.files.file; // 获取上传文件
for (let file of files) {
// 创建可读流
const reader = fs.createReadStream(file.path);
// 获取上传文件扩展名
let filePath = path.join(__dirname, 'data/') + `/${file.name}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
}
return ctx.body = "上传成功!";
});
nodejs练习笔记(四)使用koa-generater脚手架搭建项目:https://blog.csdn.net/qq_35831134/article/details/109339826