Koa2從零搭建完整工程①

寫在前面

看完了廖大神的 JavaScript 教程,特記錄一下從0搭建一個完整的 koa2 工程,主要包含:

  • 處理靜態(tài)資源
  • 模版渲染處理
  • 數(shù)據(jù)庫 ORM 處理
  • REST API 處理
  • 動態(tài)解析 controllers

目錄

  1. 創(chuàng)建 koa-basic 工程
  2. 計算響應(yīng)耗時的中間件
  3. 靜態(tài)資源處理的中間件
  4. 安裝 koa-bodyparser 中間件
  5. 模版渲染中間件
  6. ...接下一篇

創(chuàng)建 koa-basic 工程

  1. 新建文件夾 koa-basic 并使用 vscode 打開
  2. 在命令行下使用 npm init 初始化工程
  3. 使用 npm i koa -S 安裝 koa 依賴包( i 等價于 install,-S 為自動添加到 dependencies )
  4. 小小的修改一下 package.json 文件
{
  ...
  "scripts": {
    "start": "node app.js",//在命令行輸入 npm start 即可運行 app.js
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}
  1. 新建 app.js 文件
// 導入koa,和koa 1.x不同,在koa2中,我們導入的是一個class,因此用大寫的Koa表示:
const Koa = require('koa');

// 創(chuàng)建一個Koa對象表示web app本身:
const app = new Koa();

// 對于任何請求,app將調(diào)用該異步函數(shù)處理請求:
app.use(async (ctx, next) => {
    // 調(diào)用下一個中間件(等待下一個異步函數(shù)返回)
    await next();
    // 設(shè)置response的Content-Type:
    ctx.response.type = 'text/html';
    // 設(shè)置response的內(nèi)容:
    ctx.response.body = '<h1>Hello, Koa2!</h1>';
});

// 在端口3000監(jiān)聽:
app.listen(3000);
console.log('app started at port 3000...');
  1. 使用 npm start 將該 web 程序跑起來,在瀏覽器中輸入http://localhost:3000能正常訪問

計算響應(yīng)耗時的中間件

這是一個最基礎(chǔ),最簡單的中間件,所以一個異步函數(shù)就可以搞定。

//中間件1:計算響應(yīng)耗時
app.use(async (ctx, next) => {
    console.log(`Precess ${ctx.request.method} ${ctx.request.url}...`);
    var
        start = Date.now(),
        ms;
    await next();// 調(diào)用下一個中間件(等待下一個異步函數(shù)返回)
    ms = Date.now() - start;
    ctx.response.set('X-Response-Time', `${ms}ms`);
    console.log(`Response Time: ${ms}ms`);
});

靜態(tài)資源處理的中間件

先安裝mime、mz模塊

npm i -S mime
npm i -S mz

新建static文件夾用于存放靜態(tài)資源
新建static-files.js文件

const path = require('path');
const mime = require('mime');
//mz 提供的 API 和 Node.js 的 fs 模塊完全相同,但 fs 模塊使用回調(diào),而 mz 封裝了 fs 對應(yīng)的函數(shù),并改為 Promise,這樣我們就可以非常簡單的用 await 調(diào)用 mz 的函數(shù),而不需要任何回調(diào)。
const fs = require('mz/fs');

//模塊輸出為一個函數(shù)
module.exports = (pathPrefix, dir) => {
    //指定請求的前綴,默認為 static
    pathPrefix = pathPrefix || '/static/';
    //指定靜態(tài)文件目錄,默認為 static
    dir = dir || __dirname + '/static/';
    //返回異步函數(shù),這是用于 app.use() 的中間件函數(shù)
    return async (ctx, next) => {
        //請求路徑
        var rpath = ctx.request.path;
        //判斷請求路徑前綴符合要求,否則執(zhí)行下一個中間件
        if (rpath.startsWith(pathPrefix)) {
            //轉(zhuǎn)換到文件的本地路徑
            var fp = path.join(dir, rpath.substring(pathPrefix.length));
            //判斷文件存在,并返回相關(guān)內(nèi)容
            if (await fs.exists(fp)) {
                ctx.response.type = mime.getType(rpath);
                ctx.response.body = await fs.readFile(fp);
            } else {
                ctx.response.status = 404;
            }
        } else {
            await next();
        }
    };
};

app.js中使用該中間件

//中間件2:處理靜態(tài)資源,非生產(chǎn)環(huán)境下使用
if (!isProduction) {
    //引入 static-files 中間件,直接調(diào)用該模塊輸出的方法
    app.use(require('./static-files')());
}

安裝 koa-bodyparser 中間件

先安裝該模塊

npm i -S koa-bodyparser

app.js中使用該中間件

...
//在頭部引入該模塊
const bodyparser = require('koa-bodyparser');
...
//中間件3:解析原始 request 對象 body,綁定到 ctx.request.body
app.use(bodyparser());
...

模版渲染中間件

先安裝nunjucks模塊

npm i -S nunjucks

新建views文件夾用于存放模版文件
新建templating.js文件

const nunjucks = require('nunjucks');

//配置nunjucks
function createEnv(path, opts) {
    var
        autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(path, {
                noCache: noCache,
                watch: watch
            })
            , {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            }
        );

    if (opts.filters) {
        for (var f of opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}

//模塊輸出為一個函數(shù) path為可選參數(shù)
module.exports = function (path, opts) {
    //可選參數(shù)處理
    if (arguments.length === 1) {
        opts = path;//賦值給 opts
        path = null;
    }
    //模版文件目錄,默認為 views
    path = path || 'views';
    var env = createEnv(path, opts);
    //用于 app.use() 的中間件函數(shù)
    return async (ctx, next) => {
        //給 ctx 綁定 render 方法
        ctx.render = (view, model) => {
            ctx.response.type = 'text/html';
            //Object.assign()會把除第一個參數(shù)外的其他參數(shù)的所有屬性復制到第一個參數(shù)中。第二個參數(shù)是ctx.state || {},這個目的是為了能把一些公共的變量放入ctx.state并傳給View。
            ctx.response.body = env.render(view, Object.assign({}, ctx.state || {}, model || {}));
        };
        await next();
    };
};

app.js中使用該中間件

...
//在頭部引入該模塊
const templating = require('./templating');
...
//中間件4:模版文件渲染
app.use(templating({
    noCache: !isProduction,
    watch: !isProduction
}));
...

接下一篇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容