According express obtain post-parameters: body-parser uses detailed

I. Introduction

Second, the use

  Build a simple demo

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

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

  New 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)
})

  Perform node index.js,network simulation request to use Postmantools

  Do not use middleware, direct accessbody为undefined

1, JSON parser

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

  NOTE: If the simulator non JSONformat transmission, will obtain an empty JSONtarget

  urlencoded解析器即将上述代码的 jsonParser 换成 urlencodedParser 即可

2、加载到没有挂载路径的中间件
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
 

Guess you like

Origin www.cnblogs.com/goloving/p/12482994.html