Sign in

express-router: organizing routes of an app


Alpha Camp 課程中,依據不同教師,包含約 2–3 種不同 Route 分流寫法。

我選擇對於自己較易理解的寫法,歸納統整成 organizational chart (組織圖),幫助提點記憶和快速查詢。

express-router 套件 (npm 官網)

express-router is a library for organizing routes of an express application.

express-router lets you write your express routes in a simpler way.
You just have to create a ‘routes’ folder inside your project and place your routes in an index.txt file.

規劃 Route 分流,主要參與對象(檔案)共 4 個:

  1. app.js
  2. routes [Folder]
    (1) routes/index.js (總路由器)
    (2) routes/routes.js (Full-stack features)
    (3) routes/apis.js (Back-end APIs)

app.js 結構:

  1. 引入 module * 2:
    (1) 引入 express、(2) 執行 express() 套件,並存入變數 app。
  2. app.js 透過 express( ) 指定路由,使 app.js 連結 routes [Folder]require(“./routes”)(app)
  3. 匯出:module.exports = app

routes [Folder] 內 3 檔案結構:

  1. routes/index.js (總路由器)
  2. routes/routes.js (Full-stack features)
  3. routes/apis.js (Back-end APIs)

routes/index.js (總路由器) 結構:

  1. 引入 分流檔案 * 2:
    分流至 (1) routes/routes.js、(2) routes/apis.js
  2. 匯出:module.exports = (app) => {…}
    (1) app.use(“/”, routes)
    (2) app.use(“/api”, apis)
  1. routes/routes.jsroutes/apis.js 幾乎對稱相同。
  2. 兩者差異在於 routes/routes.js (Full-stack features) 須引入 passport,
    routes/apis.js (Back-end APIs) 不須再引入 passport

routes/routes.js (Full-stack features) 結構:

  1. 引入 module * 3:(1) express、(2) express.Router()、(3) passport
  2. 抽換變數名稱:所有 Route 開頭 app 改成 router
  3. 匯出:module.exports = router

routes/apis.js (Back-end APIs) 結構:

  1. 引入 module * 2:(1) express、(2) express.Router()
  2. 抽換變數名稱:所有 Route 開頭 app 改成 router
  3. 匯出:module.exports = router

Equipped with web development, communication, and business analytical skills.