Node系列-koa2开发实践

1、koa2说明

    koa2中支持了不少新的特性,最重要的是对async await的支持html

    特别注意,koa1和koa2中的不少中间件写法都不同了。node

    中间件对koa1和koa2的支持状况:https://github.com/koajs/koa/wiki
git

2、错误处理

一、能预想到的地方都加try{} catch{}语句github

二、中间件处理npm

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
        };
    }
})

三、事件监听
promise

const Koa = require('koa');
const app = new Koa();

// app.js中添加
app.on('error', (err, ctx)=>{
    console.error('server error', err, ctx);
});

3、路由处理

一、下载依赖app

npm install koa-router@next  --save

二、koa-router官网(在分支中)koa

    https://github.com/alexmingoia/koa-router/tree/koa2-async-testsasync

三、使用ui

    Todo:koa-router@7.x详解,(包括路由文件结构怎么分离)敬请期待!

4、404错误处理

// 404处理
app.use(async (ctx, next) => {
    ctx.status=404;
    ctx.body="找不到页面";
});

5、静态资源

一、下载依赖

npm install koa-static  --save

二、koa-static文档

    https://github.com/koajs/static/tree/next

三、使用

//变量定义
const path=require('path');
const Koa = require('koa');
const app = new Koa();
const staticServer = require('koa-static');


// 静态资源服务
app.use(staticServer(path.join(__dirname, 'public')));

四、访问

    根目录下有public/a.html,你直接访问localhost:3000/a.html便可得到资源

6、转换过期的generator中间件到anync中间件

    Convert koa legacy ( 0.x & 1.x ) generator middleware to modern promise middleware ( 2.x ).

    以我看这个中间件是暂时的,等到koa2的中间件丰富以后就不须要了。

一、 在使用的时候会报这个错误,因此须要一个中间件转换。

二、下载依赖

npm install koa-convert --save

三、koa-convert文档

    https://github.com/koajs/convert

四、使用

//变量定义
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'))));

7、日志记录

    没有好的,估计得本身用fs写中间件

    https://github.com/node-modules/mini-logger

8、模板引擎

http://book.apebook.org/minghe/koa-action/xtemplate/xtemplate.html

https://github.com/queckezz/koa-views

9、发送文件

一、下载依赖

npm install koa-send --save

二、文档

    https://github.com/koajs/send

三、使用

const send = require('koa-send');
const Koa = require('koa');
const app = new Koa();

app.use(async function (ctx, next){ 
    await send(ctx, ctx.path);            
})

四、注意

    上面代码中的await不能省掉,不然会报错

    上面的404处理能够返回页面了

10、表单数据处理

一、下载依赖

npm install koa-bodyparser@next --save

二、文档

    https://github.com/koajs/bodyparser/tree/next

总结

一、koa2用的仍是很爽的,用async await的写法

二、koa2新写法的插件仍是不多的不够丰富,文档也比较杂乱,不推荐用那。

免责说明

一、本博客中的文章摘自网上的众多博客,仅做为本身知识的补充和整理,并分享给其余须要的coder,不会用于商用。

二、由于不少博客的地址看完没有及时作保存,因此不少不会在这里标明出处,很是感谢各位大牛的分享,也但愿你们理解。


代码

http://git.oschina.net/shiguoqing/koa2-example

相关文章
相关标签/搜索