express獲取post傳參數據:body-parser使用詳解


一、簡介

二、使用

  搭建一個簡單的demo

mkdir body-parser-demo cd body-parser-demo npm init -y npm install express body-parser --save

  新建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) })

  執行node index.js,網絡模擬請求使用Postman工具

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

1、JSON解析器

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

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

  urlencoded解析器即將上述代碼的 jsonParser 換成 urlencodedParser 即可

2、加載到沒有掛載路徑的中間件
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })) // parse application/json
app.use(bodyParser.json())
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM