路由
路由是指應用程序的端點(URI)如何響應客戶端請求。有關路由的介紹,請參閱基本路由。
您可以使用Express app
對象的方法定義路由,這些方法對應於HTTP方法; 例如,app.get()
處理GET請求和app.post
處理POST請求。有關完整列表,請參閱app.METHOD。您還可以使用app.all()來處理所有HTTP方法,並使用app.use()將中間件指定為回調函數(有關詳細信息,請參閱使用中間件)。
實際上,路由方法可以有多個回調函數作為參數。使用多個回調函數時,重要的是提供next
回調函數的參數,然后next()
在函數體內調用以將控制權交給下一個回調。
以下代碼是一個非常基本的路由示例。
var express = require('express') var app = express() // 當發出GET請求時,返回“hello world” app.get('/', function (req, res) { res.send('hello world') })
路線方法
路由方法是從其中一個HTTP方法派生的,並附加到express
類的實例。
以下代碼是為應用程序根目錄的GET和POST方法定義的路由示例。
// GET 請求 路勁 路勁為 / 根路徑 接口返回 GET request to the homepage app.get('/', function (req, res) { res.send('GET request to the homepage') }) // POST 請求 路勁為 / 根路徑 POST request to the homepage app.post('/', function (req, res) { res.send('POST request to the homepage') })
Express支持與所有HTTP請求方法對應的方法:get
,post
等等。有關完整列表,請參閱app.METHOD。
有一種特殊的路由方法,app.all()
用於在路徑上為所有 HTTP請求方法加載中間件函數。例如,無論是使用GET,POST,PUT,DELETE還是http模塊支持的任何其他HTTP請求方法,都會對路由“/ secret”的請求執行以下處理程序。
// 只要是路勁帶 /secret 的請求 都會執行此方法
app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...') next() // 將控制傳遞給下一個處理程序 })
路線路徑
路徑路徑與請求方法相結合,定義可以進行請求的端點。路徑路徑可以是字符串,字符串模式或正則表達式(功能強大)。
字符?
,+
,*
,和()
是他們的正則表達式的對應的子集。連字符(-
)和點(.
)按字面順序由基於字符串的路徑解釋。
如果你需要$
在路徑字符串中使用美元字符(),請將其包含在([
和中])
。例如,“ /data/$book
” 處的請求的路徑字符串將是“ /data/([\$])book
”。
Express使用path-to-regexp來匹配路徑路徑; 有關定義路徑路徑的所有可能性,請參閱path-to-regexp文檔。Express Route Tester是一個用於測試基本Express路由的便捷工具,但它不支持模式匹配。
查詢字符串不是路徑路徑的一部分。
以下是基於字符串的路徑路徑的一些示例。
此路由路徑將匹配對根路由的請求/
。
app.get('/', function (req, res) { res.send('root') })
此路徑路徑將匹配請求/about
。
app.get('/about', function (req, res) { res.send('about') })
此路徑路徑將匹配請求/random.text
。
app.get('/random.text', function (req, res) { res.send('random.text') })
以下是基於字符串模式的路徑路徑的一些示例。
此路線路徑將匹配acd
和abcd
。
app.get('/ab?cd', function (req, res) { res.send('ab?cd') })
這條路線的路徑將會匹配abcd
,abbcd
,abbbcd
,等等。
app.get('/ab+cd', function (req, res) { res.send('ab+cd') })
這條路線的路徑將會匹配abcd
,abxcd
,abRANDOMcd
,ab123cd
,等。
app.get('/ab*cd', function (req, res) { res.send('ab*cd') })
此路線路徑將匹配/abe
和/abcde
。
app.get('/ab(cd)?e', function (req, res) { res.send('ab(cd)?e') })
基於正則表達式的路徑路徑示例:
此路徑路徑將匹配其中包含“a”的任何內容。
app.get(/a/, function (req, res) { res.send('/a/') })
這條路線的路徑將匹配butterfly
和dragonfly
,但不butterflyman
,dragonflyman
等。
app.get(/.*fly$/, function (req, res) { res.send('/.*fly$/') })
路線參數
路徑參數是命名的URL段,用於捕獲在URL中的位置指定的值。捕獲的值將填充在req.params
對象中,路徑參數的名稱在路徑中指定為其各自的鍵。
Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" }
要使用路由參數定義路由,只需在路徑路徑中指定路由參數,如下所示。
app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) })
路徑參數的名稱必須由“單詞字符”([A-Za-z0-9_])組成。
由於連字符(-
)和點(.
)按字面解釋,因此它們可以與路由參數一起使用以用於有用的目的。
Route path: /flights/:from-:to Request URL: http://localhost:3000/flights/LAX-SFO req.params: { "from": "LAX", "to": "SFO" } Route path: /plantae/:genus.:species Request URL: http://localhost:3000/plantae/Prunus.persica req.params: { "genus": "Prunus", "species": "persica" }
要更好地控制路由參數可以匹配的確切字符串,可以在括號(()
)中附加正則表達式:
Route path: /user/:userId(\d+) Request URL: http://localhost:3000/user/42 req.params: {"userId": "42"}
因為正則表達式通常是文字字符串的一部分,所以請確保\
例如使用額外的反斜杠轉義任何字符\\d+
。
在Express 4.x中,正則表達式中的*
字符不以通常的方式解釋。作為一種解決方法,請使用{0,}
而不是*
。這可能會在Express 5中修復。
路線處理程序
您可以提供多個回調函數,其行為類似於中間件來處理請求。唯一的例外是這些回調可能會調用next('route')
以繞過剩余的路由回調。您可以使用此機制對路徑施加前置條件,然后在沒有理由繼續當前路由的情況下將控制權傳遞給后續路由。
路由處理程序可以是函數,函數數組或兩者的組合形式,如以下示例所示。
單個回調函數可以處理路由。例如:
app.get('/example/a', function (req, res) { res.send('Hello from A!') })
多個回調函數可以處理路徑(確保指定next
對象)。例如:
app.get('/example/b', function (req, res, next) { console.log('the response will be sent by the next function ...') next() }, function (req, res) { res.send('Hello from B!') })
一組回調函數可以處理路由。例如:
var cb0 = function (req, res, next) { console.log('CB0') next() } var cb1 = function (req, res, next) { console.log('CB1') next() } var cb2 = function (req, res) { res.send('Hello from C!') } app.get('/example/c', [cb0, cb1, cb2])
獨立函數和函數數組的組合可以處理路徑。例如:
var cb0 = function (req, res, next) { console.log('CB0') next() } var cb1 = function (req, res, next) { console.log('CB1') next() } app.get('/example/d', [cb0, cb1], function (req, res, next) { console.log('the response will be sent by the next function ...') next() }, function (req, res) { res.send('Hello from D!') })
響應方法
res
下表中響應對象()的方法可以向客戶端發送響應,並終止請求 - 響應周期。如果沒有從路由處理程序調用這些方法,則客戶端請求將保持掛起狀態。
方法 | 描述 |
---|---|
res.download() | 提示下載文件。 |
重發() | 結束響應過程。 |
res.json() | 發送JSON響應。 |
res.jsonp() | 使用JSONP支持發送JSON響應。 |
res.redirect() | 重定向請求。 |
res.render() | 渲染視圖模板。 |
res.send() | 發送各種類型的回復。 |
res.sendFile() | 將文件作為八位字節流發送。 |
res.sendStatus() | 設置響應狀態代碼並將其字符串表示形式作為響應主體發送。 |
app.route()
您可以使用創建路徑路徑的可鏈接路徑處理程序app.route()
。由於路徑是在單個位置指定的,因此創建模塊化路由很有幫助,同時減少冗余和拼寫錯誤。有關路由的更多信息,請參閱:Router()文檔。
以下是使用定義的鏈接路由處理程序的示例app.route()
。
app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') })
express.Router
使用express.Router
該類創建模塊化,可安裝的路由處理程序。一個Router
實例是一個完整的中間件和路由系統; 因此,它通常被稱為“迷你應用程序”。
以下示例將路由器創建為模塊,在其中加載中間件功能,定義一些路由,並將路由器模塊安裝在主應用程序中的路徑上。
創建birds.js
app目錄中指定的路由器文件,其中包含以下內容:
var express = require('express') var router = express.Router() // middleware that is specific to this router router.use(function timeLog (req, res, next) { console.log('Time: ', Date.now()) next() }) // define the home page route router.get('/', function (req, res) { res.send('Birds home page') }) // define the about route router.get('/about', function (req, res) { res.send('About birds') }) module.exports = router
然后,在應用程序中加載路由器模塊:
var birds = require('./birds') // ... app.use('/birds', birds)
該應用程序現在能夠處理請求/birds
和/birds/about
,以及調用timeLog
中間件功能是特定的路線。