一、koa2说明
koa2中支持了很多新的特性,最重要的是对async await的支持
特别注意,koa1和koa2中的很多中间件写法都不一样了。
中间件对koa1和koa2的支持情况:https://github.com/koajs/koa/wiki
二、错误处理
1、能预想到的地方都加try{} catch{}语句
2、中间件处理
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
// will only respond with JSON
ctx.status = err.statusCode || err.status || 500;
ctx.body = {
message: err.message
};
}
})
3、事件监听
const Koa = require('koa');
const app = new Koa();
// app.js中添加
app.on('error', (err, ctx)=>{
console.error('server error', err, ctx);
});
三、路由处理
1、下载依赖
npm install koa-router@next --save
2、koa-router官网(在分支中)
https://github.com/alexmingoia/koa-router/tree/koa2-async-tests
3、使用
Todo:koa-router@7.x详解,(包括路由文件结构怎么分离)敬请期待!
四、404错误处理
// 404处理
app.use(async (ctx, next) => {
ctx.status=404;
ctx.body="找不到页面";
});
五、静态资源
1、下载依赖
npm install koa-static --save
2、koa-static文档
https://github.com/koajs/static/tree/next
3、使用
//变量定义
const path=require('path');
const Koa = require('koa');
const app = new Koa();
const staticServer = require('koa-static');
// 静态资源服务
app.use(staticServer(path.join(__dirname, 'public')));
4、访问
根目录下有public/a.html,你直接访问localhost:3000/a.html即可获得资源
六、转换过时的generator中间件到anync中间件
Convert koa legacy ( 0.x & 1.x ) generator middleware to modern promise middleware ( 2.x ).
以我看这个中间件是暂时的,等到koa2的中间件丰富之后就不需要了。
1、 在使用的时候会报这个错误,所以需要一个中间件转换。
2、下载依赖
npm install koa-convert --save
3、koa-convert文档
https://github.com/koajs/convert
4、使用
//变量定义
const path=require('path');
const Koa = require('koa');
const app = new Koa();
const staticServer = require('koa-static');
// 静态资源服务
app.use(convert(staticServer(path.join(__dirname, 'public'))));
七、日志记录
没有好的,估计得自己用fs写中间件
https://github.com/node-modules/mini-logger
八、模板引擎
http://book.apebook.org/minghe/koa-action/xtemplate/xtemplate.html
https://github.com/queckezz/koa-views
九、发送文件
1、下载依赖
npm install koa-send --save
2、文档
3、使用
const send = require('koa-send');
const Koa = require('koa');
const app = new Koa();
app.use(async function (ctx, next){
await send(ctx, ctx.path);
})
4、注意
上面代码中的await不能省掉,否则会报错
上面的404处理可以返回页面了
十、表单数据处理
1、下载依赖
npm install koa-bodyparser@next --save
2、文档
https://github.com/koajs/bodyparser/tree/next
总结
1、koa2用的还是很爽的,用async await的写法
2、koa2新写法的插件还是很少的不够丰富,文档也比较杂乱,不推荐用那。
免责说明
1、本博客中的文章摘自网上的众多博客,仅作为自己知识的补充和整理,并分享给其他需要的coder,不会用于商用。
2、因为很多博客的地址看完没有及时做保存,所以很多不会在这里标明出处,非常感谢各位大牛的分享,也希望大家理解。
代码
http://git.oschina.net/shiguoqing/koa2-example
来源:oschina
链接:https://my.oschina.net/u/1416844/blog/661915