search

Home  >  Q&A  >  body text

How do Express and request proxy remote images?

Use Node's Express combined with request to proxy remote images, but the content returned is different from the content of the original image. It is garbled, but the chaos is inconsistent.
Key code:

var FurionImgHandler = function (req, res) {
    var url = req.url.split('/fimg/')[1];
    var options = {
        url: url
    };

    function callback (error, response, body) {
        if (!error && response.statusCode === 200) {
            var contentType = response.headers['content-type'];
            response.setEncoding('binary');
            res.set('Content-Type', contentType);
            res.send(body);
        }
    }

    request.get(options, callback);
};

Original picture:

Pictures returned after proxying:

習慣沉默習慣沉默2750 days ago611

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 13:47:34

    Just add encoding: null and that’s it

    var options = {
        url: url,
        encoding: null
    };

    reply
    0
  • 阿神

    阿神2017-05-16 13:47:34

    It should be the passed Blob object. Try converting it.

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 13:47:34

    If the image does not require storage or other operations, can't it be passed directly to the response through the pipe?

    http.get(options, (response) => {
        response.pipe(res);
    })

    soonfy

    reply
    0
  • Cancelreply