参考:https://cnodejs.org/topic/55f8d70a20d84f3d377582a3
body-paser是常用的一个express中间件,主要对post请求的请求体进行解析.
安装:npm install body-parser --save
用法:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
在讲解bodyParser用法之前我们先看一下post请求的报文
POST /users/login HTTP/1.1 Host: localhost:8080 Connection: keep-alive Content-Length: 25 Pragma: no-cache Cache-Control: no-cache Origin: http://localhost:8080 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer: http://localhost:8080/users/login Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 //Cookie: _ga=GA1.1.1034300500.1513776936; Hm_lvt_b780c0c8bda0358eaaa744e0792a7d8f=1513778050; //bdshare_firstime=1513956135487; //connect.sid=s%3ApUW2dvZbb8NFkHwFENVMFdvWCFBMFSGe.jS4LiTIsgBmebRnCIips3dShG8jVCyjEs96zBNrpN4Y
其中:
Content-Type:声明报文主体的类型和编码
常见类型:
text/plain:空格转化为"+"号,但不对特殊字符进行编码;
application\json:;
application\x-www-form-urlencoded:在发送前编码所有字符(默认)【其中空格转换为 "+" 加号,特殊符号转换 为 ASCII HEX 值】;
常见的编码:
utf8和gbk;
Accept-Encoding:声明报文主体的压缩格式,有gzip、deflate、identity等
那么body-parser在请求的过程中对报文做了什么?
1,处理不同类型的请求体;比如:text、json、urlencoded等;
2,处理不同的编码;比如:utf8、gbk等;
3,处理不同的压缩类型;比如:gzip、deflare等;
4、其它边界、异常的处理;