简体   繁体   English

使用node-http-proxy访问响应头

[英]Accessing response headers using node-http-proxy

I am trying to modify the response with the help of a proxy created using node-http-proxy. 我试图借助使用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. 我想访问响应头,因为我想修改javascript文件并将修改后的javascript文件发送到客户端。

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...");
});

writeHead() doesn't necessarily have to be called with an array of headers, write() can also send headers if necessary. 不一定必须使用标头数组调用writeHead() ,如果有必要, write()也可以发送标头。

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. 我正在使用apply()将所有参数传递给旧方法,因为writeHead()实际上可以有3个参数,而您的代码仅假定有2个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM