Router Need dis

Barry YU
3 min readMar 25, 2020

--

Express 框架裡,app.js 讓開發者透過這個檔案,快速地概覽整個應用程式的配置與執行。

The File of app.js let could be very soon to view all applicaiton of setting and How to start in Express framwork

But….But….But….

In general, we do not put unlimited program code in app.js.

一般情況當你的程式碼越來越多, 不可能將全部放在一個檔案裡集中.

Example:  
The File of app.js ,have lot of app.get('/') or app.post('/') route
with controller action together .
If When you set in project really so ....savage alot

這只是一個簡單的路由…..

Create New Route middeware :

Depand with controller action ( app.js ) ~

Step 1 : Create folder :$ mkdir routes

step2 : routes / $ touch todo.js , this will be your new Route . ^__^

Step3 : move the route (_ app.get (/todo)_ ) from app.js , move to your ‘ todo.js ‘

Note: your app.js befor set of route . Now must comment out form app.get .  //app.get    XXX.  ==> cancel out , stop it

express.Router()

the Router feature already have built in module Express ,

we call it [ middleware ] . propose depand with controller action .

中文:

Express 中內建有一個名為「路由器 (Router)」 的 middleware 可以幫我們獨立處理路由與 controller action。在使用 Express 開發時,一般路由會被放到一個名為 routes(或是 routers)的資料夾來統一處理。同時,也讓我們能達成分離 controller 的目標。

😘 :

將程式碼依照功能、用途、使用頻率等特性,分門別類、整理收齊,讓專案在後續維護時更加輕鬆容易。

要在 To-do List 專案裡建立由 Express 提供的路由器,需要以下兩個步驟:

  1. 新增一個 routes/todo.js檔案,也就是我們的 todos 路由器。
  2. 把所有跟 /todos 有關的路由從 app.js 搬到 routes/todo.js 檔案。並把現在以 app 物件定義的路由改成用 express.Router 物件來定義。
  3. app.js 載入 todos 路由器。

接下來,我們會將路由器建立成模組、 在其中載入中介軟體函數,以定義我們需要的路由,並且將路由器模組裝載在主要應用程式中。

--

--

No responses yet