javascript - Node.js HTTP Proxy modify body -
i want program node.js http proxy able modify response body. have done far:
http = require('http'), httpproxy = require('http-proxy'); var proxy = httpproxy.createproxyserver(); http.createserver( function (req, res){ //here want change body guess proxy.web(req, res, { target: req.url }); }).listen(8013); i have tried use res.write(), gives me error "can't set headers after sent". don't want change headers, want change body.
how change body? suggestions appreciated.
you error because writing http response changes headers; content-length must correct.
my approach problem buffer entire response body, use cheerio parse , fiddle, , send result out client.
i accomplished monkey patching res.writehead, res.write, , res.end before handing request off http-proxy module.
function requesthandler(req, res) { var writehead = res.writehead, write = res.write, end = res.end; res.writehead = function(status, reason, headers) { if (res.headerssent) return req.socket.destroy(); // went wrong; abort if (typeof reason == 'object') headers = reason; headers = headers || {}; res.headers = headers; if (headers['content-type'] && headers['content-type'].substr(0,9) == 'text/html') { // should fiddle html responses delete headers['transfer-encoding']; // since buffer entire response, we'll send proper content-length later no transfer-encoding. var buf = new buffer(); res.write = function(data, encoding) { if (buffer.isbuffer(data)) buf = buffer.concat([buf, data]); // append raw buffer else buf = buffer.concat([buf, new buffer(data, encoding)]); // append string optional character encoding (default utf8) if (buf.length > 10 * 1024 * 1024) error('document large'); // sanity check: if response huge, bail. // ...we don't want let bring down server filling our ram. } res.end = function(data, encoding) { if (data) res.write(data, encoding); var $ = cheerio.load(buf.tostring()); // can modify response. example, $('body').append('<p>hi mom!</p>'); buf = new buffer($.html()); // have convert buffer can *byte count* (rather character count) of body res.headers['content-type'] = 'text/html; charset=utf-8'; // js deals in utf-8. res.headers['content-length'] = buf.length; // finally, send modified response out using real `writehead`/`end`: writehead.call(res, status, res.headers); end.call(res, buf); } } else { writehead.call(res, status, headers); // if it's not html, let response go through } } proxy.web(req, res, { target: req.url }); function error(msg) { // utility function report errors if (res.headerssent) end.call(res, msg); else { msg = new buffer(msg); writehead.call(res, 502, { 'content-type': 'text/plain', 'content-length': msg.length }); end.call(res, msg); } } }
Comments
Post a Comment