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

相關文章
相關標籤/搜索