From f40efe39233d61e12449092e2e789d31f5b2aa16 Mon Sep 17 00:00:00 2001 From: Florent Vilmart Date: Mon, 7 Mar 2016 23:18:45 -0500 Subject: [PATCH] Sets encoding to null to preserve raw buffers --- spec/HTTPRequest.spec.js | 11 +++++++++++ src/cloud-code/httpRequest.js | 8 +++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/spec/HTTPRequest.spec.js b/spec/HTTPRequest.spec.js index 0de220cb..e573be1a 100644 --- a/spec/HTTPRequest.spec.js +++ b/spec/HTTPRequest.spec.js @@ -217,6 +217,17 @@ describe("httpRequest", () => { done(); } }); + }); + + it('should get a cat image', (done) => { + httpRequest({ + url: 'http://thecatapi.com/api/images/get?format=src&type=jpg', + followRedirects: true + }).then((res) => { + expect(res.buffer).not.toBe(null); + expect(res.text).not.toBe(null); + done(); + }) }) it("should params object to query string", (done) => { diff --git a/src/cloud-code/httpRequest.js b/src/cloud-code/httpRequest.js index 2dc5f979..7c0b11f4 100644 --- a/src/cloud-code/httpRequest.js +++ b/src/cloud-code/httpRequest.js @@ -52,6 +52,8 @@ module.exports = function(options) { } else if (typeof options.params === 'string') { options.qs = querystring.parse(options.params); } + // force the response as a buffer + options.encoding = null; request(options, (error, response, body) => { if (error) { @@ -63,11 +65,11 @@ module.exports = function(options) { var httpResponse = {}; httpResponse.status = response.statusCode; httpResponse.headers = response.headers; - httpResponse.buffer = new Buffer(response.body); + httpResponse.buffer = response.body; httpResponse.cookies = response.headers["set-cookie"]; - httpResponse.text = response.body; + httpResponse.text = response.body.toString('utf-8'); try { - httpResponse.data = JSON.parse(response.body); + httpResponse.data = JSON.parse(httpResponse.text); } catch (e) {} // Consider <200 && >= 400 as errors if (httpResponse.status < 200 || httpResponse.status >= 400) {