body-parser 使用詳解

一、簡介

二、使用

搭建一個簡單的demo

mkdir body-parser-demo
cd body-parser-demo

npm init -y
npm install express body-parser --save

在根目錄下創(chuàng)建index.js

var express = require('express')
var bodyParser = require('body-parser')

const localPort = 3000
var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })


app.post('/login.do', (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})

app.listen(localPort, () => {
    console.log('http://127.0.0.1:%s', host, port)
})

執(zhí)行node index.js

網(wǎng)絡模擬請求使用Postman工具

Postman

不使用中間件,直接獲取body

執(zhí)行結果:

undefined

JSON解析器

app.post('/login.do', jsonParser, (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})

Postman 以raw 方式發(fā)送JSON 數(shù)據(jù),執(zhí)行結果:

{ name: 'wang', password: '123456' }

注:如果在模擬器上以非JSON格式發(fā)送,則會獲得一個空的JSON對象

urlencoded解析器

app.post('/login.do', urlencodedParser, (req, res) => {
    console.log('********************')
    console.log(req.body)

    res.end();
})
Postman

執(zhí)行結果:

{ name: 'wang', password: '123456' }

加載到?jīng)]有掛載路徑的中間件

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

具體詳見GitHub README.md

注:注意為方便測試,請求處理時直接使用end(),否則會掛起

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容