您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

用node-http-proxy重写响应头

用node-http-proxy重写响应头

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

JavaScript不是我的主要语言,因此可能有一种惯用的方法来重载writeHead方法

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 2022/1/1 18:15:44 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶