Recently, when I used node-http-proxy in my project, I encountered the need to modify the proxy server response result. The library has provided a solution to modify the response format to html: Harmon, and the return format in the project is uniformly json. It feels too bulky to use it, so I wrote a library that can parse and modify the json format.
During this period, I also encountered problems that I had not paid attention to before: http transmission encoding and node stream 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 header content-encoding: gzip/deflate* @param callback {Function} Custom modified logic*/module.exports = function modifyResponse(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 method 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('Not supported content-encoding: ' + contentEncoding);return;}// 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 logicif (typeof callback === 'function') {body = callback(body);}// Converts the JSON to buffer.body = new Buffer(JSON.stringify(body));// Call the response method 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, everyone is welcome to try out and give suggestions, and do not be stingy with Star.
In the implementation of this library, I became more and more aware of the importance of theoretical knowledge. The so-called theory is the forerunner of action. I used third-party libraries before, and I didn’t care about some underlying details.
If you have time later, you must look at the underlying implementation more, otherwise you will get stuck when you encounter difficult problems.
The above is the example code of node-http-proxy modification response result introduced to you by the editor. I hope it will be helpful to everyone!