網(wǎng)站建設(shè)步驟網(wǎng)站推廣方案范例
Express內(nèi)置的中間件
自?Express 4.16.0
?版本開始,Express
?內(nèi)置了 3 個(gè)常用的中間件,極大的提高了?Express
?項(xiàng)目的開發(fā)效率和體驗(yàn)
-
express.static
?快速托管靜態(tài)資源的內(nèi)置中間件,例如: HTML 文件、圖片、CSS
?樣式等(無(wú)兼容性) -
express.json
?解析?JSON
?格式的請(qǐng)求體數(shù)據(jù)(有兼容性,僅在?4.16.0+
?版本中可用) -
express.urlencoded
?解析?URL-encoded
?格式的請(qǐng)求體數(shù)據(jù)(有兼容性,僅在?4.16.0+
?版本中可用)
express.json
?中間件的使用
-
express.json()
?中間件,解析表單中的?JSON
?格式的數(shù)據(jù)
const express = require('express')
const app = express()// 注意:除了錯(cuò)誤級(jí)別的中間件,其他的中間件,必須在路由之前進(jìn)行配置
// 通過 express.json() 這個(gè)中間件,解析表單中的 JSON 格式的數(shù)據(jù)
app.use(express.json())app.post('/user', (req, res) => {// 在服務(wù)器,可以使用 req.body 這個(gè)屬性,來(lái)接收客戶端發(fā)送過來(lái)的請(qǐng)求體數(shù)據(jù)// 默認(rèn)情況下,如果不配置解析表單數(shù)據(jù)中間件,則 req.body 默認(rèn)等于 undefinedconsole.log(req.body)res.send('ok')
})app.listen(3000, () => {console.log('running……')
})
express.urlencoded
?中間件的使用
-
express.urlencoded
?解析?URL-encoded
?格式的請(qǐng)求體數(shù)據(jù) -
const express = require('express') const app = express()// 通過 express.urlencoded() 這個(gè)中間件,來(lái)解析表單中的 url-encoded 格式的數(shù)據(jù) 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……') })