[Fixed] 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.stack.imgur.com/HQzUc.jpg"

    console.log("Sending image");

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

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?


Change the response type of the axios request to arraybuffer:

  var image_request = await axios({
    method: "get",
    responseType: "arraybuffer", // right here
    url: "https://i.stack.imgur.com/HQzUc.jpg"

Ref: axios-config

Leave a Reply

(*) Required, Your email will not be published