Koa2學習筆記

介紹

Koa 是一個新的 web 框架,由 Express 幕后的原班人馬打造潜慎, 致力于成為 web 應用和 API 開發(fā)領域中的一個更小抹剩、更富有表現(xiàn)力、更健壯的基石绪励。 通過利用 async 函數(shù)肿孵,Koa 幫你丟棄回調(diào)函數(shù),并有力地增強錯誤處理疏魏。 Koa 并沒有捆綁任何中間件停做, 而是提供了一套優(yōu)雅的方法,幫助您快速而愉快地編寫服務端應用程序大莫。

一蛉腌、Koa2安裝

創(chuàng)建一個空白目錄,然后進入終端只厘,并在終端對koa進行安裝:

# 項目初始化
npm init -y

# 安裝koa2
npm i koa2 -S

二烙丛、入口文件

在項目根目錄創(chuàng)建 app.js 文件,并在上一步操作中生成的 package.json 里配置:

{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },
}

在 app.js 中:

const Koa = require('koa2');
const app = new Koa();
const port = 9000;

/* 
  解釋下面這段代碼:
  app.use()方法是:將給定的中間件方法添加到此應用程序羔味。簡單說就是調(diào)用中間件
  app.use() 返回 this, 因此可以鏈式表達
*/
app.use(async (ctx)=>{
    ctx.body = "Hello, Koa";
    // ctx.body是ctx.response.body的簡寫
})

app.listen(port, ()=>{
    console.log('Server is running at http://localhost:'+port);
})

然后運行 npm start 河咽,并在瀏覽器輸入 http://localhost:9000/ 即可看到頁面效果。

三赋元、洋蔥模型

學Koa必須要了解 洋蔥模型 :

1.jpg

Koa 和 Express 都會使用到中間件库北,Express的中間件是順序執(zhí)行,從第一個中間件執(zhí)行到最后一個中間件们陆,發(fā)出響應:

2.jpg

Koa是從第一個中間件開始執(zhí)行寒瓦,遇到 next 進入下一個中間件,一直執(zhí)行到最后一個中間件坪仇,在逆序杂腰,執(zhí)行上一個中間件 next 之后的代碼,一直到第一個中間件執(zhí)行結束才發(fā)出響應椅文。

3.jpg

對于這個洋蔥模型喂很,我們用代碼來解釋一下。假如把上面的代碼改寫成:

const Koa = require('koa2');
const app = new Koa();
const port = 9000;

app.use(async (ctx, next)=>{
    console.log(1)
    await next();
    console.log(1)
})

app.use(async (ctx, next)=>{
    console.log(2)
    await next();
    console.log(2)
})

app.use(async (ctx)=>{
    console.log(3)
})

app.listen(port, ()=>{
    console.log('Server is running at http://localhost:'+port);
})

那么在瀏覽器刷新后皆刺,控制臺得到的順序是:

1
2
3
2
1

現(xiàn)在可以看到少辣,我們通過 next可以先運行下個中間件,等中間件結束后羡蛾,再繼續(xù)運行當前 next() 之后的代碼漓帅。

四、路由安裝

當需要匹配不同路由時,可以安裝

npm i koa-router

將 app.js 修改:

const Koa = require('koa2');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const port = 9000;

router.get('/', async (ctx)=>{
    ctx.body = "首頁";
})

router.get('/list', async (ctx)=>{
    ctx.body = "列表頁";
})


app.use(router.routes(), router.allowedMethods());

app.listen(port, ()=>{
    console.log('Server is running at http://localhost:'+port);
})

此時忙干,到瀏覽器刷新并在地址欄最后添加 /list 即可得到首頁和列表頁器予。

備注:

// 調(diào)用router.routes()來組裝匹配好的路由,返回一個合并好的中間件
// 調(diào)用router.allowedMethods()獲得一個中間件捐迫,當發(fā)送了不符合的請求時乾翔,會返回 `405 Method Not Allowed` 或 `501 Not Implemented`

allowedMethods方法可以做以下配置:
app.use(router.allowedMethods({ 
    // throw: true, // 拋出錯誤,代替設置響應頭狀態(tài)
    // notImplemented: () => '不支持當前請求所需要的功能',
    // methodNotAllowed: () => '不支持的請求方式'
}))

五施戴、路由拆分

有時候我們需要拆分路由反浓,比如:
列表頁下所有的子路由(即前端請求的api)與首頁所有的子路由想分開處理,那么就需要拆分路由赞哗。

1雷则、創(chuàng)建 router 文件夾

創(chuàng)建router文件夾,并在其中創(chuàng)建:index.js (路由總入口文件)懈玻、home.js (首頁總路由文件)巧婶、list.js (列表頁總路由文件):

# app.js
const router = require('./router/index')
app.use(router.routes(), router.allowedMethods());

# index.js
const Router = require('koa-router');
const router = new Router();
const home = require('./home')
const list = require('./list')

router.use('/home', home.routes(), home.allowedMethods());
router.use('/list', list.routes(), list.allowedMethods());

module.exports = router;


# home.js
const Router = require('koa-router');
const home = new Router();

// 這里的 '/' 就是指向 index.js 中的 /home
home.get('/', async (ctx) => {
        ctx.body = "首頁";
    })

module.exports = home;


# list.js
const Router = require('koa-router');
const list = new Router();

list.get('/', async (ctx)=>{
    ctx.body = "列表頁";
})

module.exports = list;

到瀏覽器刷新 localhost:9000/home 與 localhost:9000/list 即可得到首頁與列表頁乾颁。

2涂乌、路由重定向

如果想直接從 localhost:9000 重定向到 localhost:9000/home
可以在 router/index.js 中做如下配置:

router.use('/home', home.routes(), home.allowedMethods());
...
router.redirect('/', '/home');

3、404無效路由

如果被訪問到無效路由英岭,可以統(tǒng)一返回404頁面:

在 router 下 errorPage.js :

const Router = require('koa-router');
const errorPage = new Router();

errorPage.get('/', async (ctx) => {
    ctx.body = "訪問頁面不存在";
})

module.exports = errorPage;

在 app.js 中引用:

// 匹配不到頁面的全部跳轉去404
app.use(async (ctx, next) => {
    await next();
    if (parseInt(ctx.status) === 404) {
        ctx.response.redirect("/404")
    }
})
app.use(router.routes(), router.allowedMethods());

六湾盒、統(tǒng)一異常處理

避免每次都要自己手寫404或200進行返回,因此我們可以創(chuàng)建 utils/errorHandler.js :

// 統(tǒng)一異常處理
module.exports = (app) => {
    app.use(async (ctx, next) => {
        let status = 0;
        let fileName = "";
        try{
            await next();
            status = ctx.status;
        }catch(err){
            //console.log(err);
            status = 500;
        }
        if(status >= 400){
            switch(status){
                case 400:
                case 404:
                case 500:
                    fileName = status;
                    break;
                default:
                    fileName = "other";
                    break;
            }
        }
        ctx.response.status = status;
        console.log(fileName);
    });
}

然后在 app.js 中引入:

const errorHandler = require('./utils/errorHandler.js');

app.use(router.routes(), router.allowedMethods());
...
errorHandler(app);

七诅妹、操作mysql函數(shù)封裝

首先罚勾,項目內(nèi)安裝 mysql:

yarn add mysql

在 utils 目錄下創(chuàng)建一個 db.js 文件:

var mysql = require('mysql')

var pool = mysql.createPool({
    host: 'localhost', // 連接的服務器(代碼托管到線上后,需改為內(nèi)網(wǎng)IP吭狡,而非外網(wǎng))
    port: 3306, // mysql服務運行的端口
    database: 'xxx', // 選擇的庫
    user: 'root', // 用戶名
    password: '123456' // 用戶密碼   
})

//對數(shù)據(jù)庫進行增刪改查操作的基礎
function query(sql,callback){
    pool.getConnection(function(err,connection){
        connection.query(sql, function (err,rows) {
            callback(err,rows)
            connection.release()
        })
    })
}

exports.query = query;

調(diào)用方式:

假設要訪問首頁('/home')時尖殃,要查詢表users中所有的數(shù)據(jù),可以如下操作:

const db = require('../utils/db.js');

home
  // 頁面底部外鏈
  .get('/', async (ctx) => {
    let data = await new Promise((resolve, reject)=>{
      let sqlLang = `select * from users`;
      db.query(sqlLang, (err, data)=>{
        if(err) reject(err);
        resolve(data);    // 返回拿到的數(shù)據(jù)
      })
    })
    ctx.body = data;
  })

八划煮、后端允許跨域

前端想跨域送丰,可以設置proxy。如果后端允許跨域弛秋,可以如下操作:

// 安裝koa2-cors
cnpm i koa2-cors

// 這里cors中間件一定要寫在路由之前
app.use(cors());
app.use(router.routes(), router.allowedMethods())

九器躏、讀取靜態(tài)資源文件

首先,在項目的根目錄下創(chuàng)建 assets 后蟹略,將圖片資源文件夾 images 放到其中登失,并且執(zhí)行以下操作:

// 安裝koa-static
cnpm install koa-static

// 引入
const path = require('path')
const static = require('koa-static')

// 獲取靜態(tài)資源文件夾
app.use(static(path.join(__dirname+'/assets')));
...
app.use(router.routes(), router.allowedMethods())

假設其中有一張圖片叫做 banner1.png,那么我們打開瀏覽器挖炬,訪問:http://localhost:5050/images/banner1.png 即可得到圖片揽浙。這里注意:

路徑上不需要寫assets,因為我們已經(jīng)指定了訪問資源時, http://localhost:5050 自動指向 assets 文件夾捏萍。

由此太抓,我們知道數(shù)據(jù)庫中圖片的地址只需要填寫 /images/banner1.png 即可。

十令杈、POST請求

1走敌、建表

設定字段為account和pwd

create table users (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    account VARCHAR(20) NOT NULL COMMENT '賬號',
    pwd VARCHAR(20) NOT NULL COMMENT '密碼',
  token LONGTEXT NOT NULL COMMENT '令牌'
);

2、form表單頁面

在 assets 下創(chuàng)建 index.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <label for="account">賬號</label>
    <input type="text" value="" name="account" class="account" placeholder="請輸入賬號" />
    <br><br>
    <label for="pwd">密碼</label>
    <input type="password" value="" name="pwd" class="pwd" placeholder="請輸入密碼" />
    <br><br>
    <button class="btn">登錄/注冊</button>
</body>
</html>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $('.btn').click(()=>{
        $.ajax({
            url: "/login/register",
            method: "POST",
            data: {
                account: $('.account').val(),
                pwd: $('.pwd').val()
            },
            success(res){
                console.log(res)
            },
            error(err){
                console.log(err)
            }
        })
    })
</script>

在瀏覽器直接訪問 http://localhost:5050/index.html 即可進入表單頁逗噩。

3掉丽、安裝中間件

安裝 koa-bodyparser 與 jsonwebtoken 中間件:

// koa-bodyparser用于獲取post請求數(shù)據(jù)
cnpm install koa-bodyparser --save

// jsonwebtoken用于生成token
cnpm install jsonwebtoken --save
JWT

在用戶登錄的路由中使用 jwt.sign 來生成token,一共定義三個參數(shù)异雁,第一個是存入token的信息捶障,第二個是token的鑰匙,和config/passport.js的配置的鑰匙相同纲刀,第三個是保存的時間项炼,3600即一個小時,最后返回token示绊,要在前面加Bearer:

const jwt = require('jsonwebtoken')

const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
let obj = {
  token,
  msg: '登錄成功'
}
resolve(obj)

4锭部、添加post接口

在 router/login.js 中加入:

const bodyParser = require('koa-bodyparser')

login.use(bodyParser());

login.post('/register', async (ctx)=>{
  console.log(ctx.request.body);        // 可以打印得到數(shù)據(jù)
    ctx.response.body = "登錄或注冊"
})

5、登錄與自動注冊

const Router = require('koa-router')
const login = new Router()
const bodyParser = require('koa-bodyparser')
const db = require('../utils/db')
const jwt = require('jsonwebtoken')

login.get('/', async (ctx) => {
    ctx.response.body = "登錄頁面"
})

login.use(bodyParser());

login.post('/register', async (ctx) => {
    let myaccount = ctx.request.body.account;
    let mypwd = ctx.request.body.pwd;
    let sql = `SELECT * FROM users WHERE account='${myaccount}'`;
    let result = await new Promise((resolve, reject) => {
        return db.query(sql, (err, data) => {
            if (err) throw err;
            if (data.length > 0) {
                resolve(data);
            } else {
                resolve(false);
            }
        })
    })
    if (result) {
        // 能找到對應的賬號
        if (result[0].pwd == mypwd) {
            // 賬號密碼正確面褐,返回token
            ctx.body = {
                token: result[0],
                msg: '登錄成功',
                account: myaccount
            };
        } else {
            // 密碼錯誤
            ctx.body = {
                msg: '密碼錯誤',
                account: myaccount
            };
        }
    } else {
        // 找不到對應的賬號拌禾,直接插入一個
        let result1 = await new Promise((resolve, reject) => {
            // 生成token
            const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
            return db.query(`INSERT INTO users (account, pwd, token) values ('${myaccount}', '${mypwd}', '${token}')`, (error, datas) => {
                if (error) throw error;
                // 已插入數(shù)據(jù),返回用戶名與token
                let obj = {
                    token,
                    msg: '登錄成功',
                    account: myaccount
                }
                resolve(obj)
            })
        })
        if (result1) {
            ctx.body = result1;
        }
    }
})

module.exports = login;

此時展哭,前端做這個post請求后湃窍,就會得到相應的數(shù)據(jù)。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末匪傍,一起剝皮案震驚了整個濱河市您市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌役衡,老刑警劉巖茵休,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異映挂,居然都是意外死亡泽篮,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門柑船,熙熙樓的掌柜王于貴愁眉苦臉地迎上來帽撑,“玉大人,你說我怎么就攤上這事鞍时】骼” “怎么了扣蜻?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長及塘。 經(jīng)常有香客問我莽使,道長,這世上最難降的妖魔是什么笙僚? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任芳肌,我火速辦了婚禮,結果婚禮上肋层,老公的妹妹穿的比我還像新娘亿笤。我一直安慰自己,他們只是感情好栋猖,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布净薛。 她就那樣靜靜地躺著,像睡著了一般蒲拉。 火紅的嫁衣襯著肌膚如雪肃拜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天雌团,我揣著相機與錄音燃领,去河邊找鬼。 笑死辱姨,一個胖子當著我的面吹牛柿菩,可吹牛的內(nèi)容都是我干的戚嗅。 我是一名探鬼主播雨涛,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼懦胞!你這毒婦竟也來了替久?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤躏尉,失蹤者是張志新(化名)和其女友劉穎蚯根,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體胀糜,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡颅拦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了教藻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片距帅。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖括堤,靈堂內(nèi)的尸體忽然破棺而出碌秸,到底是詐尸還是另有隱情绍移,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布讥电,位于F島的核電站蹂窖,受9級特大地震影響,放射性物質發(fā)生泄漏恩敌。R本人自食惡果不足惜瞬测,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望纠炮。 院中可真熱鬧涣楷,春花似錦、人聲如沸抗碰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽弧蝇。三九已至碳褒,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間看疗,已是汗流浹背沙峻。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留两芳,地道東北人摔寨。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像怖辆,于是被迫代替她去往敵國和親是复。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容