前言
- 目的:觀察和理解 Middleware 中的:
(1) app.use、(2) next()、(3) Router 順序,對 request 流向的影響。 - 方法:建立一組 Router 設定檔(範例),包含 4 組設定
(Name代稱[Router])和最終回傳 JSON:
(1) Kevin [app.use]
(2) John [POST/me]
(3) Jimmy [app.use*]
(4) Mary [GET/me]
(5) Final JSON:res.json({answer: req.name})
Express-Using middleware
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.
Middleware functions are functions that have access to the request object (
req
), the response object (res
), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable namednext
.Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call
next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.An Express application can use the following types of middleware:
1. Application-level middleware
You can load application-level and router-level middleware with an optional mount path. You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
推理&驗證方式:
- 自建小專案,實際觀察結果,設置 console.log 印出:
(1) 標記編號、(2) Name 代稱。 - 理解 app.use 和 next()觀念,建立一些假設和推測 Route 可能流向。
- POST:透過 POSTMAN 發送 POST request 時,終端機也會印出console.log。
範例:[Folder] Node.js -> [Folder] test-route-sequelize
重點概述:
- app.use:
(1) 表示 request 皆會經過 app.use 路由
(2) 注意:不代表會優先經過,要依據上下位置順序。 - Kevin 和 Jimmy 屬於 app.use,路由路徑皆會經過 app.use,而 Kevin位置在 Jimmy 上方,所以順序上,Kevin 先、Jimmy 後。
- 注意:若發送 POST/me,John 位置順序在 Jimmy 上方,所以先經過John,再經過 Jimmy。
- next():將 request 往下遞交給後續的 middleware 流程。
情境一、Route 呼叫 GET:
- 印出:{“answer”: “Jimmy”}
- 流程:
(1) Kevin [app.use] -> (3) Jimmy [app.use*]
-> (5)Final JSON: 印出 Jimmy
情境二、Route 呼叫 GET /me:
- 印出:{“answer”: “Mary”}
- 流程:
(1) Kevin [app.use] -> (3) Jimmy [app.use*] -> (4) Mary [GET/me]
-> (5) Final JSON: 印出 Mary
※ 注意:
Jimmy [app.use*] 的*代表該 Route 目錄下所有字串皆符合,所以 /me 也包含在*條件內。
情境三、Route 呼叫 POST /me:
- 印出:{“answer”: “Jimmy”}
- 流程:
(1) Kevin [app.use] -> (2) John [POST/me] -> (3) Jimmy [app.use*]
-> (5) Final JSON: 印出 Jimmy - 說明:John 順序在 Jimmy 上方,所以先經過 John,再經過 Jimmy。
※ 注意:
POST 要使用 POSTMAN API 測試工具發送 POST request,同時終端機可 console.log 印出。