簡體   English   中英

使用node-http-proxy訪問響應頭

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

我試圖借助使用node-http-proxy創建的代理來修改響應。 但是,我無法訪問響應頭。 我想訪問響應頭,因為我想修改javascript文件並將修改后的javascript文件發送到客戶端。

這是我的代碼:

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() ,如果有必要, write()也可以發送標頭。

如果要訪問標題(或設置標題),可以使用以下命令:

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

我正在使用apply()將所有參數傳遞給舊方法,因為writeHead()實際上可以有3個參數,而您的代碼僅假定有2個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM