经过看源代码下面的说明知道了body-parser的三种用法:
在讲用法之间,我们需要弄清楚下面四个不同的处理方法:这四个处理方法分别对body的内容采用不同的处理方法;分别是处理json数据、Buffer流数据、文本数据、UTF-8的编码的数据。
bodyParser.json(options)、bodyParser.raw(options)、bodyParser.text(options)、bodyParser.urlencoded(options)
以下是它的三种用法:
1、底层中间件用法:这将拦截和解析所有的请求;也即这种用法是全局的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var
express = require(
'express'
)
var
bodyParser = require(
'body-parser'
)
var
app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended:
false
}))
// parse application/json
app.use(bodyParser.json())
app.use(
function
(req, res) {
res.setHeader(
'Content-Type'
,
'text/plain'
)
res.write(
'you posted:\n'
)
res.end(JSON.stringify(req.body,
null
, 2))
})
|
express的use方法调用body-parser实例;且use方法没有设置路由路径;这样的body-parser实例就会对该app所有的请求进行拦截和解析。
2、特定路由下的中间件用法:这种用法是针对特定路由下的特定请求的,只有请求该路由时,中间件才会拦截和解析该请求;也即这种用法是局部的;也是最常用的一个方式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
var
express = require(
'express'
)
var
bodyParser = require(
'body-parser'
)
var
app = express()
// create application/json parser
var
jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var
urlencodedParser = bodyParser.urlencoded({ extended:
false
})
// POST /login gets urlencoded bodies
app.post(
'/login'
, urlencodedParser,
function
(req, res) {
if
(!req.body)
return
res.sendStatus(400)
res.send(
'welcome, '
+ req.body.username)
})
// POST /api/users gets JSON bodies
app.post(
'/api/users'
, jsonParser,
function
(req, res) {
if
(!req.body)
return
res.sendStatus(400)
// create user in req.body
})
|
express的post(或者get)方法调用body-parser实例;且该方法有设置路由路径;这样的body-parser实例就会对该post(或者get)的请求进行拦截和解析。
3、设置Content-Type 属性;用于修改和设定中间件解析的body类容类型。
// parse various different custom JSON types as JSON app.use(bodyParser.json({ type: 'application/*+json' }); // parse some custom thing into a Buffer app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })); // parse an HTML body into a string app.use(bodyParser.text({ type: 'text/html' }));