nodejs-析请求体-v1.0.0

入门基础

POST /test HTTP/1.1
Host: 127.0.0.1:3000
Content-Type: text/plain; charset=utf8
Content-Encoding: gzip

chyingp

请求报文主体的内容类型:常见的类型有text/plain、application/json、application/x-www-form-urlencoded。
请求报文主体的内容编码:常见的编码有utf8、gbk等。
请求报文主体的具体内容:chyingp
请求报文主体的压缩格式:常见的取值有gzip、deflate、identity。

简单示例

/*
采用默认编码,不对请求体进行压缩。请求体类型为text/plain。
即:
Content-Type: text/plain; charset=utf8
Content-Encoding: identity
*/
//step-01:建服务器
//plain-server.js
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);

//step-02:启服务器
node plain-server.js

//step-03:建客户端
//plain-client.js
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');

//step-04:启客户端
node plain-client.js

/*
采用默认编码,不对请求体进行压缩。请求体类型为application/json。
即:
Content-Type: application/json; charset=utf8
Content-Encoding: identity
*/

//step-01:建服务器
//json-server.js
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);

//step-02:启服务器
node json-server.js

//step-03:建客户端
//json-client.js
var http = require('http');

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) );

//step-04:启客户端
node json-client.js


/*
采用默认编码,不对请求体进行压缩。请求体类型为application/x-www-form-urlencoded。
即:
Content-Type: application/x-www-form-urlencoded; charset=utf8
Content-Encoding: identity
*/
//step-01:建服务器
//urlencode-server.js
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);

//step-02:启服务器
node urlencode-server.js

//step-03:建客户端
//urlencode-client.js
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) );

//step-04:启客户端
node urlencode-client.js


/*
采用gbk编码,不对请求体进行压缩。请求体类型为默认类型。
即:
Content-Type: text/plain; charset=gbk
Content-Encoding: identity
*/
//step-01:建服务器
//gbk-server.js
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);

//step-02:启服务器
node gbk-server.js

//step-03:建客户端
//gbk-client.js
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);

//step-04:启客户端
node gbk-client.js


/*
采用默认编码,对请求体进行gzip压缩。请求体类型为默认类型。
即:
Content-Type: text/plain; charset=utf-8
Content-Encoding: gzip
*/
//step-01:建服务器
//gzip-server.js
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);
//step-02:启服务器
node gzip-server.js

//step-03:建客户端
//gzip-client.js
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);

//step-04:启客户端
node gzip-client.js

相关文档

http://www.cnblogs.com/chyingp/p/nodejs-learning-express-body-parser.html

你可能感兴趣的:(nodejs-析请求体-v1.0.0)