Node.js 实现一个body-parse中间件
bodyParse.js
const fs = require('fs');
const querystring = require('querystring');
const qs = require('qs');
function BodyParser() {
}
// 解析 application/x-www-form-urlencoded 数据
BodyParser.prototype.urlencoded = function (options = {}) {
const { extended = false } = options;
return function (req, res, next) {
const contentType = req.headers['content-type'];
if (contentType == 'application/x-www-form-urlencoded') {
const buf = [];
req.on('data', data => {
buf.push(data);
})
req.on('end', () => {
const result = Buffer.concat(buf).toString();
req.body = extended ? qs.parse(result) : querystring.parse(result);
next();
})
} else {
next();
}
}
}
// 解析 application/json 数据
BodyParser.prototype.json = function (options = {}) {
return function (req, res, next) {
const contentType = req.headers['content-type'];
if (contentType == 'application/json') {
const buf = [];
req.on('data', data => {
buf.push(data);
})
req.on('end', () => {
const result = Buffer.concat(buf).toString();
req.body = JSON.parse(result);
next();
})
} else {
next();
}
}
}
// 解析 text/plain 数据
BodyParser.prototype.text = function (options = {}) {
return function (req, res, next) {
const contentType = req.headers['content-type'];
if (contentType == 'text/plain') {
const buf = [];
req.on('data', data => {
buf.push(data);
})
req.on('end', () => {
const result = Buffer.concat(buf).toString();
req.body = result;
next();
})
} else {
next();
}
}
}
module.exports = new BodyParser();
server.js
const express = require('express');
const app = express();
// const bodyParser = require('body-parser'); // body-parse 中间件
const bodyParser = require('./bodyParser'); // 自己写的body-parse
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.post('/user', (req, res) => {
const body = req.body;
res.send(body);
})
app.listen(3000, () => console.log('server running at http://localhost:3000'));
test.js
const http = require('http');
const iconv = require('iconv-lite');
//发送时必须附带Content-Type请求头
const options = {
host: 'localhost',
port: 3000,
method: 'POST',
path: '/user',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'application/json'
// 'Content-Type': 'text/plain'
}
}
// 用node http模块进行请求.
const request = http.request(options, response => {
// 将response返回的数据通过pipe管道输出到控制台
response.pipe(process.stdout);
})
request.end('name=huzhixin&age=20');
// request.end('{"name":"huzhixin","age":20}');
// request.end('胡志欣');