NPM-body-parser正文解析器

安装

1
$ npm install body-parser

使用

1
2
3
4
5
mkdir body-parser-demo
cd body-parser-demo

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

在根目录下创建index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 网络模拟请求  

不使用中间件,直接获取body执行结果:

undefined

JSON解析器

1
2
3
4
5
6
app.post('/login.do', jsonParser, (req, res) => {
console.log('********************')
console.log(req.body)

res.end();
})

Postman 以raw 方式发送JSON 数据,执行结果:

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

注:如果在模拟器上以非JSON格式发送,则会获得一个空的JSON对象 urlencoded解析器

1
2
3
4
5
6
app.post('/login.do', urlencodedParser, (req, res) => {
console.log('********************')
console.log(req.body)

res.end();
})
  • 版权声明: 本博客所有文章,未经许可,任何单位及个人不得做营利性使用!转载请标明出处!如有侵权请联系作者。
  • Copyrights © 2015-2023 翟天野

请我喝杯咖啡吧~