1. 程式人生 > 實用技巧 >第三方中介軟體 body-parser解析表單資料

第三方中介軟體 body-parser解析表單資料

第三方中介軟體
  1. Express 官方內建,而是由第三方開發出來的中介軟體,叫做第三方中介軟體。在專案中,大家可以按需下載並配置第三方中介軟體,從而提高專案的開發效率

  2. 例如:在 [email protected] 之前的版本中,經常使用 body-parser 這個第三方中介軟體,來解析請求體資料。使用步驟如下

    • 執行 npm install body-parser 安裝中介軟體

    • 使用 require 匯入中介軟體

    • 呼叫 app.use() 註冊並使用中介軟體

  3. 注意:Express 內建的 express.urlencoded 中介軟體,就是基於 body-parser 這個第三方中介軟體進一步封裝出來的

  4. 案例程式碼

const express = require('express')
const app = express()

// 1. 匯入解析表單資料的中介軟體 body-parser
const bodyParser = require('body-parser')

// 通過 express.urlencoded() 這個中介軟體,來解析表單中的 url-encoded 格式的資料
// app.use(express.urlencoded({ extended: false }))

// 2. 使用 app.use() 註冊中介軟體
app.use(bodyParser.urlencoded({ extended: false
})) app.post('/book', (req, res) => { console.log(req.body) res.send(req.body) }) app.listen(3000, () => { console.log('running……') })