1. 程式人生 > >Node.js使用Koa搭建 基礎專案

Node.js使用Koa搭建 基礎專案

目錄

一、建立專案
二、配置路由
三、靜態資源
四、模板引擎
五、結語
Koa 是由 Express 原班人馬打造的超輕量服務端框架
與 Express 相比,除了自由度更高,可以自行引入中介軟體之外,更重要的是使用了 ES6 + async,從而避免了回撥地獄
不過也是因為程式碼升級,所以 Koa2 需要 v7.60 以上的 node.js 環境

一、建立專案
手動建立一個專案目錄,然後快速生成一個 package.json 檔案
npm init -y

安裝 koa //當前版本 2.4.1
npm install koa -S

然後建立一個 app.js

`// app.js`
`const Koa = require(``'koa'``);`
`const app =` `new` `Koa();`
`app.use(async ctx => {`
`ctx.body =` `'Wise Wrong'``;`
`});`
`app.listen(3000);`

最後在 package.json 中新增啟動指令

image
一個最基礎的 koa 應用就這樣完成了

image
可以執行 npm start 並在瀏覽器訪問http://localhost:3000/ 檢視效果
如果覺得手動建立專案太過繁瑣,可以使用腳手架 koa-generato 來生成專案

npm install koa-generator -g
koa2 project_name

然後在專案下 npm install 安裝依賴,npm start 啟動專案
如果是剛接觸 koa,建議先看完這篇部落格,再使用腳手架工具,這樣能更好的理解各個依賴包的作用

二、配置路由
上面 app.js 中有一個 ctx,這是一個 Koa 提供的 Context 物件,封裝了 request 和 response
每一次 HTTP Request 都會建立一個 Context 物件
我們可以通過 Context.request.path 來獲取使用者請求的路徑,然後通過 Context.response.body 給使用者傳送內容
Koa 預設的返回型別是 text/plain,如果要返回一個 html 檔案(或者一個模組檔案),就需要修改 Context.response.type
另外,Context.response 可以簡寫,比如 Context.response.type 簡寫為 Context.type,Context.response.body 簡寫為 Context.type
在專案下建立一個存放 html 檔案的目錄 views,並在該目錄下建立一個 index.html,然後修改 app.js

`// app.js// 原生路由`
`const Koa = require(``'koa'``);`
`const fs = require(``'fs'``);`
`const app =` `new` `Koa();`
`app.use(async (ctx, next) => {`
`if` `(ctx.request.path ===` `'/index'``) {`
`ctx.type =` `'text/html'``;`
`ctx.body = fs.createReadStream(``'./views/index.html'``);`
`}` `else` `{`
`await next();`
`}`
`});`
`app.listen(3000);`

然後在瀏覽器中訪問 就能看到 index.html 頁面,而訪問別的地址則是 not found

這樣處理 url 顯得特別笨拙,所以我們需要引入路由中介軟體 koa-router

npm install koa-router -S

需要注意的是,在匯入 koa-router 的時候,需要在末尾加一個括號:

const router = require('koa-router')();

相當於:

const koaRouter = require(``'koa-router'``);
const router = koaRouter();

建立一個 routes 目錄,用來存放路由檔案,並在目錄下建立 index.js

image
`// routes/index.js`
`const fs = require(``'fs'``);`
`const router = require(``'koa-router'``)()`
`router.get(``'/index'``, async (ctx, next) => {`
`ctx.type =` `'text/html'``;`
`ctx.body = fs.createReadStream(``'./views/index.html'``);`
`});`
`module.exports = router`

這裡還可以使用 prefix 方法,為檔案中的所有介面新增一個 baseUrl

// router.prefix(’/about’)
修改 app.js

`// app.js`
`const Koa = require(``'koa'``);`
`const app =` `new` `Koa();`
`const index = require(``'./routes/index'``)`
`app.use(index.routes(), index.allowedMethods())`
`app.listen(3000);`

上面的 allowedMethods 用於校驗請求的方法,如果用 post 請求訪問 get 介面,就會直接返回失敗

另外,還可以在 url 中新增變數,然後通過 Context.params.name 訪問

`router.get(``'/about/:name'``, async (ctx, next) => {`
`ctx.body = `I am ${ctx.params.name}!`;`
`});`

三、靜態資源
在上面的 index.html 中,如果需要引入 css 等靜態資源,就需要用到 [koa-static]

npm install koa-static -S

建立一個目錄 public 用來存放靜態資源

image
然後在 app.js 中新增以下程式碼

`const static = require(``'koa-static'``);`
`// 將 public 目錄設定為靜態資源目錄`
`const main = static(__dirname +` `'/public'``);`
`app.use(main);`

事實上,這三行程式碼還可以優化

pp.use(require('koa-static')(__dirname + ‘/public’``));

然後就能在 index.html 中引入對應的檔案了

image
四、模板引擎
上面的路由是使用 fs 模組直接讀取 html 檔案
開發的時候更推薦使用 koa-views 中介軟體來渲染頁面

npm install koa-views -S

在 app.js 中將 views 目錄設定為模版目錄

`const views = require(``'koa-views'``)`
`app.use(views(__dirname +` `'/views'``));`
然後在路由檔案中,就能使用 render 方法了

`// routes/index.js`
`const router = require(``'koa-router'``)()`
`router.get(``'/index'``, async (ctx, next) => {`
`await ctx.render(``'index'``);`
`});`
`module.exports = router`

以上是直接渲染 html 檔案的方法,如果要引入模板引擎,可以新增 extension 欄位來設定模版型別

`app.use(views(__dirname +` `'/views'``, {`
`extension:` `'pug'` `// 以 pug 模版為例`
`}))`

五、結語
如果將 Express 看作 webstorm,那麼 Koa 就是 sublime

當 Express 流行的時候,其冗雜的依賴項被很多開發者所詬病

所以 Express 團隊將 Express 拆卸得只剩下最基本的骨架,讓開發者自行組裝,這就是 Koa

正如文中所說,從零開始太過繁瑣,可以使用腳手架 koa-generato 來快速開發

不過我更推薦,在熟悉了 Koa 之後,搭一個適合自己專案的腳手架

不然為何不直接用 Express 呢

我想這也是 Koa 的官方文件中沒有提到 generato 工具的原因吧**瞭解更多**
在這裡插入圖片描述