简体   繁体   English

使用NodeJS + Request模块时无法正确代理图像

[英]Images are not proxied correctly when using NodeJS + Request module

I have a proxy that works well (as far as I can tell) UNTIL I attempt to proxy images (or perhaps any binary data?). 我有一个运行良好的代理(据我所知),直到我尝试代理图像(或任何二进制数据?)。 By my estimations, the below code should work, but it does not. 据我估计,下面的代码应该可以,但是不能。 I'm sure I"m doing something obviously dumb, but I've been digging through forums and apis and I have yet to hit upon the correct approach. 我敢肯定我在做一些显然很愚蠢的事情,但是我一直在研究论坛和api,但尚未找到正确的方法。

The 'core' of my proxy looks something like the following. 我的代理服务器的“核心”如下所示。

  function(req, res) {
    ...

    options = {
      url: 'a url',
      headers: {
        'Authorization': auth
      }
    };

    request(options,
      function(e, r, b){
        var encoding = (r.headers['content-type'].indexOf('image') === -1) ? 'utf8' : 'binary';

        res.writeHead(200, {
          'Content-Length': r.headers['content-length'],
          'Content-Type': r.headers['content-type']
        });

        if (encoding === 'binary') {
          b = new Buffer(b);
        }

        res.end(b, encoding);
      });
    }

What am I missing here? 我在这里想念什么?

Thanks in advance for any and all help! 在此先感谢您提供的所有帮助!

My problem was not with the response (as I though originally), but rather the fact that the request module was encoding it's response body to unicode by default, when disabled ( encoding: null ), the response body is converted to a buffer which is easily consumed by the response. 我的问题不是响应(就像我最初那样),而是请求模块默认将其响应主体编码为unicode的事实,当禁用时( encoding: null ),响应主体将转换为缓冲区容易被响应消耗掉。

    options = {
      url: url,
      encoding: null,
      headers: {
        'Authorization': auth
      }
    };

    request(options,
      function(e, r, b){
        var encoding = (r.headers['content-type'].indexOf('image') === -1) ? 'utf8' : 'binary';
        res.end(b, encoding);
      });

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

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