Nodejs 进阶:Express 常用中间件 body-parser 实现解析
本文摘录自《Nodejs学习笔记》,更多章节及更新,请访问 github主页地址。欢迎加群交流,群号 197339705。
写在前面
body-parser是非常常用的一个express中间件,作用是对post请求的请求体进行解析。使用非常简单,以下两行代码已经覆盖了大部分的使用场景。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
本文从简单的例子出发,探究body-parser的内部实现。至于body-parser如何使用,感兴趣的同学可以参考官方文档。
入门基础
在正式讲解前,我们先来看一个POST请求的报文,如下所示。
POST /test HTTP/1.1
Host: 127.0.0.1:3000
Content-Type: text/plain; charset=utf8
Content-Encoding: gzip
chyingp
其中需要我们注意的有Content-Type、Content-Encoding以及报文主体:
- Content-Type:请求报文主体的类型、编码。常见的类型有
text/plain、application/json、application/x-www-form-urlencoded。常见的编码有utf8、gbk等。 - Content-Encoding:声明报文主体的压缩格式,常见的取值有
gzip、deflate、identity。 - 报文主体:这里是个普通的文本字符串
chyingp。
body-parser主要做了什么
body-parser实现的要点如下:
- 处理不同类型的请求体:比如
text、json、urlencoded等,对应的报文主体的格式不同。 - 处理不同的编码:比如
utf8、gbk等。 - 处理不同的压缩类型:比如
gzip、deflare等。 - 其他边界、异常的处理。
一、处理不同类型请求体
为了方便读者测试,以下例子均包含服务端、客户端代码,完整代码可在笔者github上找到。
解析text/plain
客户端请求的代码如下,采用默认编码,不对请求体进行压缩。请求体类型为text/plain。
var http = require('http');
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Encoding': 'identity'
}
};
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
client.end('chyingp');
服务端代码如下。text/plain类型处理比较简单,就是buffer的拼接。
var http = require('http');
var parsePostBody = function (req, done) {
var arr = [];
var chunks;
req.on('data', buff => {
arr.push(buff);
});
req.on('end', () => {
chunks = Buffer.concat(arr);
done(chunks);
});
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (chunks) => {
var body = chunks.toString();
res.end(`Your nick is ${body}`)
});
});
server.listen(3000);
解析application/json
客户端代码如下,把Content-Type换成application/json。
var http = require('http');
var querystring = require('querystring');
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'identity'
}
};
var jsonBody = {
nick: 'chyingp'
};
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
client.end( JSON.stringify(jsonBody) );
服务端代码如下,相比text/plain,只是多了个JSON.parse()的过程。
var http = require('http');
var parsePostBody = function (req, done) {
var length = req.headers['content-length'] - 0;
var arr = [];
var chunks;
req.on('data', buff => {
arr.push(buff);
});
req.on('end', () => {
chunks = Buffer.concat(arr);
done(chunks);
});
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (chunks) => {
var json = JSON.parse( chunks.toString() ); // 关键代码
res.end(`Your nick is ${json.nick}`)
});
});
server.listen(3000);
解析application/x-www-form-urlencoded
客户端代码如下,这里通过querystring对请求体进行格式化,得到类似nick=chyingp的字符串。
var http = require('http');
var querystring = require('querystring');
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'form/x-www-form-urlencoded',
'Content-Encoding': 'identity'
}
};
var postBody = { nick: 'chyingp' };
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
client.end( querystring.stringify(postBody) );
服务端代码如下,同样跟text/plain的解析差不多,就多了个querystring.parse()的调用。
var http = require('http');
var querystring = require('querystring');
var parsePostBody = function (req, done) {
var length = req.headers['content-length'] - 0;
var arr = [];
var chunks;
req.on('data', buff => {
arr.push(buff);
});
req.on('end', () => {
chunks = Buffer.concat(arr);
done(chunks);
});
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (chunks) => {
var body = querystring.parse( chunks.toString() ); // 关键代码
res.end(`Your nick is ${body.nick}`)
});
});
server.listen(3000);
二、处理不同编码
很多时候,来自客户端的请求,采用的不一定是默认的utf8编码,这个时候,就需要对请求体进行解码处理。
客户端请求如下,有两个要点。
- 编码声明:在
Content-Type最后加上;charset=gbk - 请求体编码:这里借助了
iconv-lite,对请求体进行编码iconv.encode('程序猿小卡', encoding)
var http = require('http');
var iconv = require('iconv-lite');
var encoding = 'gbk'; // 请求编码
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'text/plain; charset=' + encoding,
'Content-Encoding': 'identity',
}
};
// 备注:nodejs本身不支持gbk编码,所以请求发送前,需要先进行编码
var buff = iconv.encode('程序猿小卡', encoding);
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
client.end(buff, encoding);
服务端代码如下,这里多了两个步骤:编码判断、解码操作。首先通过Content-Type获取编码类型gbk,然后通过iconv-lite进行反向解码操作。
var http = require('http');
var contentType = require('content-type');
var iconv = require('iconv-lite');
var parsePostBody = function (req, done) {
var obj = contentType.parse(req.headers['content-type']);
var charset = obj.parameters.charset; // 编码判断:这里获取到的值是 'gbk'
var arr = [];
var chunks;
req.on('data', buff => {
arr.push(buff);
});
req.on('end', () => {
chunks = Buffer.concat(arr);
var body = iconv.decode(chunks, charset); // 解码操作
done(body);
});
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (body) => {
res.end(`Your nick is ${body}`)
});
});
server.listen(3000);
三、处理不同压缩类型
这里举个gzip压缩的例子。客户端代码如下,要点如下:
- 压缩类型声明:
Content-Encoding赋值为gzip。 - 请求体压缩:通过
zlib模块对请求体进行gzip压缩。
var http = require('http');
var zlib = require('zlib');
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Encoding': 'gzip'
}
};
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
// 注意:将 Content-Encoding 设置为 gzip 的同时,发送给服务端的数据也应该先进行gzip
var buff = zlib.gzipSync('chyingp');
client.end(buff);
服务端代码如下,这里通过zlib模块,对请求体进行了解压缩操作(guzip)。
var http = require('http');
var zlib = require('zlib');
var parsePostBody = function (req, done) {
var length = req.headers['content-length'] - 0;
var contentEncoding = req.headers['content-encoding'];
var stream = req;
// 关键代码如下
if(contentEncoding === 'gzip') {
stream = zlib.createGunzip();
req.pipe(stream);
}
var arr = [];
var chunks;
stream.on('data', buff => {
arr.push(buff);
});
stream.on('end', () => {
chunks = Buffer.concat(arr);
done(chunks);
});
stream.on('error', error => console.error(error.message));
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (chunks) => {
var body = chunks.toString();
res.end(`Your nick is ${body}`)
});
});
server.listen(3000);
写在后面
body-parser的核心实现并不复杂,翻看源码后你会发现,更多的代码是在处理异常跟边界。
另外,对于POST请求,还有一个非常常见的Content-Type是multipart/form-data,这个的处理相对复杂些,body-parser不打算对其进行支持。篇幅有限,后续章节再继续展开。
欢迎交流,如有错漏请指出。
相关链接
https://github.com/expressjs/body-parser/
https://github.com/ashtuchkin/iconv-lite
Nodejs 进阶:Express 常用中间件 body-parser 实现解析的更多相关文章
- express常用中间件
整理一下工作中经常使用到的Express中间件 config-lite: 读取配置文件 不同环境下配置文件使用 - Node实战 config-lite express-session: sessio ...
- [转] Nodejs 进阶:Express 常用中间件 body-parser 实现解析
写在前面 body-parser是非常常用的一个express中间件,作用是对post请求的请求体进行解析.使用非常简单,以下两行代码已经覆盖了大部分的使用场景. app.use(bodyParser ...
- NodeJS学习笔记 进阶 (3)Nodejs 进阶:Express 常用中间件 body-parser 实现解析(ok)
个人总结:Node.js处理post表单需要body-parser,这篇文章进行了详细的讲解. 摘选自网络 写在前面 body-parser是非常常用的一个express中间件,作用是对http请求体 ...
- 77.深入理解nodejs中Express的中间件
转自:https://blog.csdn.net/huang100qi/article/details/80220012 Express是一个基于Node.js平台的web应用开发框架,在Node.j ...
- 【nodejs】--express的中间件multer实现图片文件上传--【XUEBIG】
Multer是nodejs中处理multipart/form-data数据格式(主要用在上传功能中)的中间件.该中间件不处理multipart/form-data数据格式以外的任何形式的数据 Tips ...
- nodejs之express的中间件
express中间件分成三种 内置中间件 static 自定义中间件 第三方中间件 (body-parser) (拦截器) 全局自定义中间件 在请求接口时 有几个接口都要验证传来的内容是否存在或者是否 ...
- Nodejs之express第三方核心模块的中间件——body-parser
Node中的核心模块分两类:一类是自带的核心模块,如http.tcp等,第二类是第三方核心模块,express就是与http对应的第三方核心模块,用于处理http请求.express在3.0版本中自带 ...
- Express使用进阶:cookie-parser中间件实现深入剖析
文章导读 cookie-parser是Express的中间件,用来实现cookie的解析,是官方脚手架内置的中间件之一. 它的使用非常简单,但在使用过程中偶尔也会遇到问题.一般都是因为对Express ...
- nodeJs,Express中间件是什么与常见中间件
中间件的功能和分类 中间件的本质就是一个函数,在收到请求和返回相应的过程中做一些我们想做的事情.Express文档中对它的作用是这么描述的: 执行任何代码.修改请求和响应对象.终结请求-响应循环.调用 ...
随机推荐
- emmet(快速开发)的使用
emmet可以帮助您快速编写HTML和CSS代码,从而加速Web前端开发. 比如<html>.<head>.<body>等,现在你只需要1秒钟就可以输入这些标签. ...
- 36.java_exception_test
package mytext1; class TZException extends Exception{ TZException(String str){ super(str); } public ...
- (转)Python 遍历List三种方式
转自: http://www.cnblogs.com/pizitai/archive/2017/02/14/6398276.html # 方法1 print '遍历列表方法1:' for i in l ...
- python去除文本中的HTML标签
def SplitHtmlTag(file): with open(file,"r") as f,open("result.txt","w+" ...
- 使用RandomAccessFile类对文件进行读写
1. RandomAccessFile类简介 前面一篇随笔<File类遍历目录及文件>中有说到,File类只能用于表示文件或目录的名称.大小等信息,而不能用于文件内容的访问.而当需要访 ...
- USACO Section 1.1-2 Greedy Gift Givers
Greedy Gift Givers 贪婪的送礼者 对于一群(NP个)要互送礼物的朋友,GY要确定每个人送出的钱比收到的多多少. 在这一个问题中,每个人都准备了一些钱来送礼物,而这些钱将会被平均分给那 ...
- Jsoup抓取、解析网页和poi存取excel综合案例——采集网站的联系人信息
需求:采集网站中每一页的联系人信息 一.创建maven工程,添加jsoup和poi的依赖包 <!-- https://mvnrepository.com/artifact/org.apache. ...
- uoj#228 基础数据结构练习题
题面:http://uoj.ac/problem/228 正解:线段树. 我们可以发现,开根号时一个区间中的数总是趋近相等.判断一个区间的数是否相等,只要判断最大值和最小值是否相等就行了.如果这个区间 ...
- 接口加密《二》: API权限设计总结
来源:http://meiyitianabc.blog.163.com/blog/static/105022127201310562811897/ API权限设计总结: 最近在做API的权限设计这一块 ...
- endsWith is not a function解决方案
在写javascript脚本时,用某些方法,有时候会碰到"XXX is not a function"之类的报错. 出现这种情况,主要是因为某些方法在低版本浏览器上不支持.比如说& ...