Node.js响应奇怪的编码? [英] Node.js weird encoding on response?

查看:518
本文介绍了Node.js响应奇怪的编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方API来获取响应给我的一些图像。我不认为这是base64?

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"

发出请求的代码。

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

我的问题是,对于node.js,如何对此进行解码以便我可以向客户端发送一个正确的图片?

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

推荐答案

决议:

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();
});

参考: 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.

这篇关于Node.js响应奇怪的编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆