Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

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?

Upvotes: 3

Views: 8333

Answers (2)

num8er
num8er

Reputation: 19372

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.

Upvotes: 3

AEQ
AEQ

Reputation: 1429

The 3rd-party API should have the data-type of what the expected response type is, so that we can figure out what the format is that needs to be decoded...

My guess is that its returning a UTF-8 string, try this modules' decode function to decode the string: https://www.npmjs.com/package/utf8

Upvotes: 0

Related Questions