简体   繁体   English

node-http-proxy设置img请求标头

[英]node-http-proxy set img request headers

Is it possible to set request headers for img src attributes, using node-http-proxy? 是否可以使用node-http-proxy设置img src属性的请求标头? I'm getting a 401 error because my server is expecting a header property: value for every request, incuding img src attributes. 我收到401错误,因为我的服务器需要一个标头属性:每个请求的值,包括img src属性。 I'm setting the headers for all requests in the index.js file but headers are not being set for img requests. 我正在为index.js文件中的所有请求设置标头,但未为img请求设置标头。 I'm trying to check if the request is for an image and then set the header before sending the request using node-http-proxy. 我正在尝试检查请求是否针对图像,然后在使用node-http-proxy发送请求之前设置标头。

  // index.js -- works for non img src requests
  if ($rootScope.foobar_header !== undefined) {
    headersGetter()['X-Special-Proxy-Header'] = $rootScope.foobar_header; 
  }
  if (data) { 
      return angular.toJson(data);
  }

function proxyMiddleware(req, res, next) { 函数proxyMiddleware(req,res,next){

  if (req.url.indexOf(proxyApiPrefix) !== -1) {
      if (req.url.indexOf(proxyImgPrefix) !== -1) {
        console.log('img request');
        proxy.on('proxyReq', function(proxyReq, req, res, options) {
            proxyReq.setHeader('X-Special-Proxy-Header', 'foobar_header');
        });
      }
    proxy.web(req, res);
  } else {
    next();
  }
}

I think you need to setup the proxy.on... bit before you run your server, rather than inside some middleware, although it's hard to be sure without seeing more code. 我认为您需要在运行服务器之前,而不是在某些中间件中,先设置proxy.on... ,尽管很难确保没有看到更多代码。

The docs show that you could do something like this: 文档显示您可以执行以下操作:

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  if (req.url.indexOf(proxyApiPrefix) !== -1) {
    if (req.url.indexOf(proxyImgPrefix) !== -1) {
      console.log('img request');
      proxyReq.setHeader('X-Special-Proxy-Header', 'foobar_header');
    }
  }
});

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

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