1

I am trying to modify the response with the help of a proxy created using node-http-proxy. However I am not able to access the response headers. I want to access the response headers since I would like to modify javascript files and send the modified javascript files to the client.

This is my code:

var httpProxy = require('http-proxy');
var url = require('url');
var i = 0;

httpProxy.createServer(function(req, res, next) {
    var oldwriteHead = res.writeHead;
    res.writeHead = function(code, headers) {
        oldwriteHead.call(res, code, headers);
        console.log(headers); //this is undefined
    };
    next();
}, function(req, res, proxy) {
    var urlObj = url.parse(req.url);

    req.headers.host = urlObj.host;
    req.url = urlObj.path;

    proxy.proxyRequest(req, res, {
        host: urlObj.host,
        port: 80,
        enable: {xforward: true}
    });
}).listen(9000, function() {
    console.log("Waiting for requests...");
});

1 Answer 1

2

writeHead() doesn't necessarily have to be called with an array of headers, write() can also send headers if necessary.

If you want to access headers (or set them), you can use this:

res.writeHead = function() {
  // To set:
  this.setHeader('your-header', 'your-header-value');

  // To read:
  console.log('Content-type:', this.getHeader('content-type'));

  // Call the original method !!! see text
  oldwriteHead.apply(this, arguments);
};

I'm using apply() to pass all the arguments to the old method, because writeHead() can actually have 3 arguments, while your code only assumed there were two.

Sign up to request clarification or add additional context in comments.

3 Comments

Since the last argument to writeHead() was optional, I created a function of only 2 arguments. Thanks for the clarification!
how to access all the headers in the response though?
You can read this._headers (although the underscore suggests that you really shouldn't rely on it being present in future versions, but there's — as far as I can see — no other way to access them otherwise).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.