The most recent use of node-http-proxy in projects involves modifying the demand for proxy response results, which has provided a scenario for modifying the response format to HTML: Harmon, while the return format in the project is unified as JSON, it feels too cumbersome to use it. So I wrote a library that can parse and modify the JSON format.
There have also been problems that were not previously noticed: HTTP transmission coding, node flow related processing. Here is the implementation code:
var zlib = require (' zlib ');
var concatstream = require (' Concat-stream '); /** * Modify The response of JSON * @param res {response} The HTTP response * @param contentencoding {String} the HTTP Hea Der Content-encoding:gzip/deflate * @param callback {function} Custom modified logic */module.exports = function Modifyr Esponse (res, contentencoding, callback) {var unzip, zip;/Now only deal with the gzip and deflate content-encoding. If (contentencoding = = ' gzip ') {unzip = zlib.
Gunzip (); Zip = zlib.
Gzip (); else if (contentencoding = = ' deflate ') {unzip = zlib.
Inflate (); Zip = zlib.
Deflate ();
//The cache response can be called after the modification.
var _write = Res.write;
var _end = res.end; if (unzip) {Unzip.on (' error '), function (e) {console.log (' Unzip error: ', e); _end.call (res);});} else {Console.log (' N
OT supported content-encoding: ' + contentencoding);
Return
The//The rewrite response method is replaced by unzip stream. Res.write = function (data) {Unzip.wriTE (data);
};
Res.end = function (data) {unzip.end (data);};
Concat the unzip stream. var concatwrite = Concatstream (function (data) {var body, try {BODY = Json.parse (data.tostring ()); \ catch (e) {BODY =
Data.tostring ();
Console.log (' Json.parse error: ', e);
}//Custom modified logic if (typeof callback = = ' function ') {BODY = callback (body);}//Converts the JSON to buffer.
BODY = new Buffer (json.stringify);
Call the response and recover the content-encoding.
Zip.on (' Data ', function (chunk) {_write.call (res, chunk);});
Zip.on (' End ', function () {_end.call (res);});
Zip.write (body);
Zip.end ();
});
Unzip.pipe (Concatwrite); };
Project Address: Node-http-proxy-json, you are welcome to try to advise, while not stingy with star.
In the realization process of the library more and more feel the importance of theoretical knowledge, the so-called theory is the forerunner of action, before the use of Third-party libraries, also did not care about some of the low-level details of processing.
There is time to look at the bottom of the implementation, otherwise encountered difficult problems will be stuck.
The above is a small set for you to introduce the Node-http-proxy modify the response result instance code, I hope to help you!