简体   繁体   中英

node-http-proxy set img request headers

Is it possible to set request headers for img src attributes, using node-http-proxy? I'm getting a 401 error because my server is expecting a header property: value for every request, incuding img src attributes. I'm setting the headers for all requests in the index.js file but headers are not being set for img requests. 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.

  // 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) {

  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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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