Nodejs中Express 常用中间件 body-parser 实现解析

2020-06-17 05:48:34易采站长站整理

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