// 通过报头的Transfer-Encoding或Content-Length即可判断请求中是否带有内容
var hasBody = function(req) {
return 'transfer-encoding' in req.headers || 'content-length' in req.headers;
};
// 在HTTP_Parser解析报头结束后,报文内容部分会通过data事件触发
function (req, res) {
if (hasBody(req)) {
var buffers = [];
req.on('data', function (chunk) {
buffers.push(chunk);
});
req.on('end', function () {
req.rawBody = Buffer.concat(buffers).toString();
handle(req, res);
});
} else {
handle(req, res);
}
}
表单数据:最为常见的数据提交就是通过网页表单提交数据到服务器端:
<form action="/upload" method="post">
<label for="username">Username:</label> <input type="text" name="username" id="username" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
// 默认的表单提交,请求头的Content-Type字段值为application/x-www-form-urlencoded
// 即:Content-Type: application/x-www-form-urlencoded
// 解析
var handle = function(req, res) {
if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
req.body = querystring.parse(req.rawBody);
}
todo(req, res);
};
其他格式: JSON和XML文件等,判断和解析他们的原理都比较相似,都是依据Content-Type中的值决定,其中JSON类型的值
为application/json,XML的值为application/xml
// JSON文件
// 对于Node来说,要处理它不需要额外的任何库
var handle = function(req, res) {
if (mime(req) === 'application/json') {
try {
req.body = JSON.parse(req.rawBody);
} catch (e) {
// 异常内容,响应Bad request
res.writeHead(4000);
res.end('Invalid JSON);
return;
}
}
todo(req, res);
};
// XML文件
var xml2js = require('xml2js');
var handle = function (req, res) {
if (mime(req) === 'application/xml') {
xml2js.parseString(req.rawBody, function (err, xml) {
if (err) {
// 异常内容, 响应Bad request
res.writeHead(400);
res.end('Invalid XML');
return;
}
req.body = xml;
todo(req, res);
});
}
};