Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using node-http-proxy and want to watch for a particular response header and rewrite it if necessary. Anyone here have suggestions on to do this?

My proxy server sits in front of a couple different node servers as well as a java webapp. The java app is setting a cookie, but the cookie has a path that is relative the the webapp's context. I need the cookie to be secure and have a path to root without modifying the Java application.

In other words, the following header is returned:

set-cookie: MYSPECIALCOOKIE=679b6291-d1cc-47be; Path=/app; HttpOnly

And I'd like to rewrite the Path value to:

set-cookie: MYSPECIALCOOKIE=679b6291-d1cc-47be; Path=/; HttpOnly; Secure

I'm not clear how I would do this using node-http-proxy. Suggestions? Is there middleware to help with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
467 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can achieve this by overloading the writeHead function of the response object. For example, this code will set the 'foo' response header to the value 'bar'. I've indicated where you can add your own logic to change the header values.

JavaScript is not my primary language, so there may be a more idiomatic way to overload the writeHead method.

httpProxy = require('http-proxy');

httpProxy.createServer(function (req, res, proxy) {

  res.oldWriteHead = res.writeHead;
  res.writeHead = function(statusCode, headers) {
    /* add logic to change headers here */
    var contentType = res.getHeader('content-type');
    res.setHeader('content-type', 'text/plain');

    // old way: might not work now
    // as headers param is not always provided
    // https://github.com/nodejitsu/node-http-proxy/pull/260/files
    // headers['foo'] = 'bar';       

    res.oldWriteHead(statusCode, headers);
  }

  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: 3000
  });
}).listen(8000);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...