express之中间件---body-parser解析

经过看源代码下面的说明知道了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' }));
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值