Express內置的中間件
自 Express 4.16.0
版本開始,Express
內置了 3 個常用的中間件,極大的提高了 Express
項目的開發效率和體驗
-
express.static
快速托管靜態資源的內置中間件,例如: HTML 文件、圖片、CSS
-
express.json
解析JSON
格式的請求體數據(有兼容性,僅在4.16.0+
版本中可用) -
express.urlencoded
解析URL-encoded
格式的請求體數據(有兼容性,僅在4.16.0+
版本中可用)
express.json
中間件的使用
-
express.json()
中間件,解析表單中的JSON
格式的數據 -
案例代碼
const express = require('express') const app = express() // 注意:除了錯誤級別的中間件,其他的中間件,必須在路由之前進行配置 // 通過 express.json() 這個中間件,解析表單中的 JSON 格式的數據 app.use(express.json()) app.post('/user', (req, res) => { // 在服務器,可以使用 req.body 這個屬性,來接收客戶端發送過來的請求體數據 // 默認情況下,如果不配置解析表單數據中間件,則 req.body 默認等於 undefined console.log(req.body) res.send('ok') }) app.listen(3000, () => { console.log('running……') })
express.urlencoded
中間件的使用
-
express.urlencoded
解析URL-encoded
格式的請求體數據 -
案例代碼
const express = require('express') const app = express() // 通過 express.urlencoded() 這個中間件,來解析表單中的 url-encoded 格式的數據 app.use(express.urlencoded({ extended: false })) app.post('/book', (req, res) => { console.log(req.body) res.send(req.body) }) app.listen(3000, () => { console.log('running……') })