知新 | koa框架入門到熟練第一章

介紹

koa,是基於Node.js 平臺的下一代的web開發框架。
是由Express原班人馬打造,致力於成爲一個更小的,更加富有表現力的,web框架。
使用koa編寫web應用,能夠免除重複的回調函數嵌套,並極大的提升錯誤處理的效率,
koa框架不單單在內核方法中能夠綁定任何中間件,它僅僅提供了一個輕量級,優雅的函數庫,思路和express相差很多。node

koa框架的安裝

安裝koa

安裝koa框架和安裝以前的模塊同樣。
使用以下命令安裝web

npm install --save koa

使用save參數,代表將會自動修改package.json 文件。自動添加依賴項express

hello world

輸入以下的代碼,運行hello worldnpm

const koa = require("koa");
const app = new koa();


// 配置中間件
app.use(async (ctx) => {
    ctx.body = "hello world";
})

// 監聽端口
app.listen(3000);

運行文件json

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js

輸出結果以下promise

異步的處理

因爲js是單線程的,因此,使用回調函數處理異步等問題。app

回調函數處理

const koa = require("koa");
const app = new koa();


function getData(callback){
    setTimeout(function () {
        var name = "ming";
        callback(name);
    }, 1000)
}

// 從外部獲取異步方法裏的數據
getData(function (data) {
    console.log(data)
})

// 監聽端口
app.listen(3000);

輸出結果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

使用promise處理異步

const koa = require("koa");
const app = new koa();


// promise 處理異步
// resolve 成功的回調函數
// reject 失敗的回調函數

var p = new Promise(function (resolve, reject) {
    setTimeout(function () {
        var name = "張三";
    }, 1000)
})

// 獲取異步的結果
p.then((data) => {
    console.log(data);
}) 

// 監聽端口
app.listen(3000);

運行結果以下框架

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

關於async await promise

其中async是異步的縮寫,await被認爲是async wait的縮寫,因此,async用於申明一個函數爲異步的,await用於等待一個異步方法執行完成。koa

簡單理解

async 讓方法變成異步
await 等待異步方法執行完成。異步

async

實際例子

這裏使用實際的例子,更好理解。

同步函數

function getData(){
    return "ming";
}
console,log(getData())

輸出結果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

async 可讓該方法變成異步

const koa = require("koa");
const app = new koa();


// promise 處理異步
// resolve 成功的回調函數
// reject 失敗的回調函數

async function getData(){
    return "這是一個數據";
}

console.log(getData());

// 監聽端口
app.listen(3000);

輸出結果以下所示

其中promise爲一個異步的數據

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
Promise { '這是一個數據' }

獲取該數據

const koa = require("koa");
const app = new koa();


// promise 處理異步
// resolve 成功的回調函數
// reject 失敗的回調函數

async function getData(){
    return "這是一個數據";
}

var p = getData();

p.then((data) => {
    console.log(data);
})

// 監聽端口
app.listen(3000);

輸出結果如圖所示

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
這是一個數據

await

使用await方法獲取到異步的信息

const koa = require("koa");
const app = new koa();


// promise 處理異步
// resolve 成功的回調函數
// reject 失敗的回調函數

async function getData(){
    return "這是一個數據";
}

async  function test(){
    // 此時運行的爲,發現該函數是一個異步函數,遇到了await進入等待狀態,等待getData執行完畢,再往下執行
    var d = await  getData();

    console.log(d)
}

test()

// 監聽端口
app.listen(3000);

運行結果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
這是一個數據

koa 路由

路由是根據不一樣的url地址,加載不一樣頁面實現不一樣的功能。

安裝路由

npm install --save koa-router

使用路由

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", (ctx, next) => {
    ctx.body = "ming";
})

// 啓動路由
app.use(router.routes());
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

運行結果以下所示

其中能夠添加async做爲異步方法來調用

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {
    ctx.body = "ming";
})

// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

獲取連接的參數值

經過router獲取路由的參數值
連接爲

獲取格式化好的

http://localhost:3000/?ming=3

代碼爲

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.query)

    ctx.body = "ming";
})

// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

訪問的結果是

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
[Object: null prototype] { ming: '3' }

獲取未格式化好的

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming=3
const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.querystring)

    ctx.body = "ming";
})

// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

設置動態路由

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// 配置動態路由
router.get("/:id", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.params)

    ctx.body = "ming";
})

// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

訪問的連接爲

http://localhost:3000/ming

輸出的內容

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
{ id: 'ming' }

koa 中間件

這裏配置koa的中間件
中間件就是匹配路由完成作的一系列的操做,把它稱之爲中間件。

中間件的功能主要有:

  1. 執行任何代碼
  2. 修改請求和響應的對象
  3. 終結請求,響應循環
  4. 調用堆棧中的下一個中間件。

需求: 打印出中間件相關內容

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// 中間件
app.use(async (ctx) => {
    ctx.body = "這是一箇中間件";
})


// 配置動態路由
router.get("/:id", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.params)

    ctx.body = "ming";
})



// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

運行結果

此時訪問任何頁面出現的都是這個內容,

持續匹配

由於訪問的時候,沒有加上next,此時形成的沒法進入到匹配路由的階段。

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// 中間件
app.use(async (ctx, next) => {
    ctx.body = "這是一箇中間件";

    // 進入路由匹配
    next();
})


// 配置動態路由
router.get("/:id", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.params)

    ctx.body = "ming";
})



// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

因爲js是單線程的,此時須要添加await,進行訪問。

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// 中間件
app.use(async (ctx, next) => {
    ctx.body = "這是一箇中間件";

    // 進入路由匹配
    await next();
})


// 配置動態路由
router.get("/:id", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.params)

    ctx.body = "ming";
})



// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

路由持續匹配

路由因爲沒有await next,形成路由匹配到之後就再也不匹配,因此添加next,能把兩個相同的路由按照順序,匹配完成。

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// 中間件
app.use(async (ctx, next) => {
    ctx.body = "這是一箇中間件";

    // 進入路由匹配
    await next();
})


// 配置動態路由
router.get("/:id", async (ctx, next) => {

    // query 返回的是格式化好的參數對象
    // querystring 返回的是請求的字符串

    console.log(ctx.params)

    ctx.body = "ming";
    
    await next();
})
router.get("/:id", async (ctx, next) => {
    // 此時匹配到這點
    await  next();
})



// 啓動路由
app.use(router.routes());
// 設置響應頭
app.use(router.allowedMethods());


// 監聽端口
app.listen(3000);

中間件的執行順序

通常是洋蔥模型,做爲中間件的執行順序。

錯誤處理中間件

// 中間件
app.use(async (ctx, next) => {
    console.log("這是一箇中間件");
    
    // 進入洋蔥
    next()
    
    // 出洋蔥
    if(ctx.status = 404){
        ctx.status = 404;
        ctx.body = "這是一個 404 頁面";
    }
})

第三方中間件

例如進行靜態文件託管的時候,使用的是第三方中間件

const static = require('koa-static');
const staticPath = './static';

app.use(static(
    path.join(__dirname, staticPath);
))

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

這樣就完成了靜態文件託管

相關文章
相關標籤/搜索