Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js weird encoding on response?

I am using a third party api to get some images the response gives me this. I don't think this is base64?

"����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0000\b\u0006\u0006\u0007\u0006\u0005\b\u0007\u0007\u0007\t\t\b\n\f\u0014\r\f\u000b\u000b\f\u0019\u0012\u0013\u000f\u0014\u001d\u001a\u001f\u001e\u001d\u001a\u001c\u001c $.' \",#\u001c\u001c(7),01444\u001f'9=82<.342��\u0000C\u0001\t\t\t\f\u000b\f\u0018\r\r\u00182!\u001c!22222222222222222222222222222222222222222222222222��\u0000\u0011\b\u0002!\u0002&\u0003\u0001\"\u0000\u0002\u0011\u0001\u0003\u0011\u0001��\u0000\u001f\u0000\u0000\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b��\u0000"

The code that makes the request.

unirest.get("MYAPIROUTE")
.header("X-Mashape-Key", "MYKEY")
.end(function (result) {
  console.log(result.status, result.headers, result.body);
  res.send(result.body);
});

My question is, with node.js how do I decode this so I can send the client a proper image?

like image 381
Michael Joseph Aubry Avatar asked Nov 19 '25 06:11

Michael Joseph Aubry


1 Answers

Resolution:

unirest.get("MYAPIROUTE")
.header("X-Mashape-Key", "MYKEY")
.end(function (result) {
  console.log(result.status, result.headers, result.body);

  if(result.status==200) {
     var buffer = (new Buffer(result.body.toString()));
     res.end(buffer.toString("base64")); // output content as response body

     require('fs').writeFileSync('/some/public/folder/md5HashOfRequestedUrl.jpg', buffer);  // also write it to file

     delete buffer;
     return;
  }

  res.writeHead(result.status, result.headers);
  res.write(result.body);
  res.end();
});

reference: http://nodejs.org/api/buffer.html

let's say it's an image. so why not to try to set

<img src="http://your-site.com/some/public/folder/md5HashOfRequestedUrl.jpg">

also You can write response to file in temporary public folder to avoid doing same requests to somewhere.

like image 55
num8er Avatar answered Nov 21 '25 18:11

num8er



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!