Node.js + Express 介面請求(GET、POST、PUT)事例
路由
路由是指應用程式的端點(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 homepageapp.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()
// 只要是路勁帶 /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
中介軟體功能是特定的路線。