middleware - bodyparser

express4以前,bodyparser是express下的一个对象。javascript

express4把bodyparser分离出来。java

 

本文中的实例基于如下的这个请求node

$.ajax({
  url: '/save',
  type: 'post',
  data: {
    info: {
      nane: 'henry',
      age: 30
    },
    hobby: ['sport', 'coding']
  }
});

通常来讲express在接收到这个请求时,收到的请求参数是这样的ajax

app.post('/save', function(req, res, next){
  console.log(req.body);
  /* {'info[name]': 'henry', 'info[age]': '30', hobby[1]: 'sport', 'hobby[2]': 'coding'} */
});

显然,这样的数据是不能直接使用的。express

再看看使用bodyparser后的状况json

app.use(bodyparser.urlencode());
app.post('/save', function(req, res, next){
  console.log(req.body);
  /* {'info': {'name': 'henry', 'age': '30'}, 'hobby': ['sport', 'coding']} */
});

bodyparser会将解析后的请求参数覆盖到req.body, 后面的中间件能够继续访问该属性。app

 


 

常见的http请求的Content - type有如下几种post

  • application/x-www-form-urlencoded 常见的form提交
  • multipart/form-data 文件提交
  • application/json 提交json格式的数据
  • text/xml 提交xml格式的数据
  • text/plain 提交纯文本

其中bodyparser.urlencode中间件用于解析application/x-www-form-urlencoded的请求参数性能

bodyparser.json中间件用于解析application/json的请求参数url

 

另外,urlencode中间件有一个可配置的参数({extended: boolean});

这个参数为真时,中间件将使用qs模块解析请求参数,为假时使用nodejs自带的querystring来解析请求参数。

默认值是true。可是这个已经不被express官方推荐了。

 

来看看二者的区别

app.use(bodyparser.urlencode({extend: true}));
  /* 这也是默认配置 */
app.post('/save', function(req, res, next){
  console.log(req.body); 
  /* {'info': {'name': 'henry', 'age: '30'}, 'hobby': ['sport', 'coding']} */
});

另外一种状况,使用querystring解析

app.use(bodyparser.urlencode({extended: false}));
app.post('/save', function(req, res, next){
  console.log(req.body);
  /* {'info[name]': 'henry', 'info[age]': '30', 'hobby[1]': 'sport', hobby[2]: 'coding'} */
});

能够看出来querystring没有很好的解析嵌套对象。因此,用qs来解析是比较合适。

可是qs自身也有涉及一些性能问题,致使解析对象的嵌套层数超过5层之后就不继续解析了。

 

通常来讲,jq的ajax方法默认配置和form表单提交所使用的Content - type

都是application/x-www-form-urlencoded,而且提交的数据也不会有很深的嵌套,

使用qs来解析就足够了。可是若是非要上传复杂嵌套的数据,能够经过修改http请求的

Content-type 为 application/json便可。

相关文章
相关标签/搜索