Steve
Steve

Reputation: 90

How to Respond in Express with a JPG Data String?

router.get("/photos", function(req, res) {
    // Get the image
    var image_request = await axios({
            method: "get",
            url: "https://i.sstatic.net/HQzUc.jpg"
    });

    console.log("Sending image");
    console.log(image_request.headers);

    res.set('Content-Type', image_request.headers["content-type"]);
    res.set('Content-Length', image_request.data.length);
    res.send(image_request.data);
}

There's a problem with how I'm formatting the Get response. First, I tried excluding both res.set(...), but that ended up with Postman receiving image_request.data as a string with Content-Type="text/html; charset=utf-8"

With both res.set(...), on Postman, I am getting Content-Type="image/jpeg; charset=utf-8", but the image's format seems to be wrong. Postman Response Body

What's the problem with what I'm trying to send as the response? And is there a better alternative to what I'm trying to do?

Upvotes: 1

Views: 312

Answers (1)

hoangdv
hoangdv

Reputation: 16157

Change the response type of the axios request to arraybuffer:

  var image_request = await axios({
    method: "get",
    responseType: "arraybuffer", // right here
    url: "https://i.sstatic.net/HQzUc.jpg"
  });

Ref: axios-config

Upvotes: 1

Related Questions