body-parser的使用

最近在学习项目的过程中接触到了node.js。学习过程中,对express框架的一些语法和中间件不是很明白。比如说body-parser。为什么要使用它?它有什么作用?这篇就来对body-parser做一下笔记。

bodyParser中间件

bodyParser中间件用来解析http请求体,是express默认使用的中间件之一。那么首先就要引入bodyParser

 使用express生成一个网站,它默认已经使用了bodyParser.json与bodyParser.urlencoded的解析功能,除了这两个,bodyParser还支持对text、raw的解析。

 那么顾名思义,bodyParser.json是用来解析json数据格式的。bodyParser.urlencoded则用来解析我们通常的form表单提交的数据,也就是请求头中包含这样的信息:

 Content-Type: application/x-www-form-urlencoded

常见的四种Content-Type类型:

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

详细解读 urlencoded

bodyParser.urlencoded模块用于解析req.body的数据,解析成功后覆盖原来的req.body。如果解析失败则为{}。该模块有一个属性extended,官方介绍如下:

The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true).

Defaults to true, but using the default has been deprecated.

大致的意思就是:extended选项允许配置使用querystring(false)或qs(true)来解析数据,默认值是true,但这已经是不被赞成的了。

querystring就是nodejs内建的对象之一,用来字符串化对象或解析字符串。如

querystring.parse("name=henry&age=30") => { name: 'henry', age: '30' }

猜你喜欢

转载自www.cnblogs.com/lovekiku123/p/11961094.html