Content-Length Header is Incorrect
Not sure if this is an express
issue or with http-proxy
but I am modifying (extending) the response body and the resulting Content-Length
header is not getting extended. When I try to extend it with proxyRes.headers
this does not get passed on to the client and there is no res.headers
method/hashmap.
const express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
app.get('/', (req, res) => {
apiProxy.web(req, res, {target: MYB});
});
apiProxy.on('proxyRes', (proxyRes, req, res) => {
var _write = res.write;
var body = '';
proxyRes.on('data', function(data) {
data = data.toString('utf-8');
body += data;
});
res.write = function(data) {
try {
if (res.statusCode === 200 && proxyRes.headers['content-type'] === 'text/html') {
// body.length is 411 bytes
body = body.replace('</body>', '<hr>© aaa 2022 Marc Cawood</body>');
// body.length is now 425 bytes
proxyRes.headers['content-length'] = Buffer.byteLength(body, 'utf-8');
_write.call(res, body);
// Browser still gets Content-Length: 411 :-(
}
} catch (e) {
console.trace(e);
console.error(e.message);
throw e;
}
};
});