用node-http-proxy重写响应头 [英] Rewrite response headers with node-http-proxy

查看:373
本文介绍了用node-http-proxy重写响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node-http-proxy ,并希望注意特别的回应 标头,并在必要时将其重写.这里的任何人都有建议 这样吗?

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?

我的代理服务器位于几个不同的节点服务器前面, 以及一个Java webapp. Java应用正在设置Cookie,但是 Cookie的路径相对于Webapp的上下文.我需要 cookie是安全的,并且具有无需修改Java即可到达root的路径 应用程序.

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

我想将Path值重写为:

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

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

我不清楚如何使用node-http-proxy做到这一点.有什么建议吗? 有中间件可以帮助您解决此问题吗?

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

推荐答案

您可以通过重载响应对象的writeHead函数来实现.例如,此代码会将"foo"响应标头设置为值"bar".我已经指出了可以在其中添加自己的逻辑以更改标头值的地方.

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不是我的主要语言,因此可能有一种惯用的方法来重载writeHead方法.

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);

这篇关于用node-http-proxy重写响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆