From 71d7e3a04b180b37b96918aa22418322d813d45c Mon Sep 17 00:00:00 2001 From: achingbrain Date: Fri, 14 Aug 2020 14:43:19 +0100 Subject: [PATCH] fix: handle non-printable characters in browser responses Fixes a regression introduced by #54 - in the browser by default the response body is interpreted as a string which can become corrupted when non-printable characters are encountered. --- package.json | 3 ++- src/http/fetch.browser.js | 2 ++ test/http.spec.js | 11 +++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index b0c212b..cd894f9 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,8 @@ "delay": "^4.3.0", "it-all": "^1.0.2", "it-drain": "^1.0.1", - "it-last": "^1.0.2" + "it-last": "^1.0.2", + "uint8arrays": "^1.1.0" }, "contributors": [ "Hugo Dias ", diff --git a/src/http/fetch.browser.js b/src/http/fetch.browser.js index 08d1319..dfb4a20 100644 --- a/src/http/fetch.browser.js +++ b/src/http/fetch.browser.js @@ -50,6 +50,8 @@ const fetch = (url, options = {}) => { request.upload.onprogress = options.onUploadProgress } + request.responseType = 'arraybuffer' + return new Promise((resolve, reject) => { /** * @param {Event} event diff --git a/test/http.spec.js b/test/http.spec.js index 2e48a01..e63e047 100644 --- a/test/http.spec.js +++ b/test/http.spec.js @@ -10,6 +10,8 @@ const drain = require('it-drain') const all = require('it-all') const { isBrowser, isWebWorker } = require('../src/env') const { Buffer } = require('buffer') +const uint8ArrayFromString = require('uint8arrays/from-string') +const uint8ArrayEquals = require('uint8arrays/equals') describe('http', function () { it('makes a GET request', async function () { @@ -175,4 +177,13 @@ describe('http', function () { expect(upload).to.be.greaterThan(0) expect(download).to.be.greaterThan(0) }) + + it('makes a GET request with unprintable characters', async function () { + const buf = uint8ArrayFromString('a163666f6f6c6461672d63626f722d626172', 'base16') + const params = Array.from(buf).map(val => `data=${val.toString()}`).join('&') + + const req = await HTTP.get(`${process.env.ECHO_SERVER}/download?${params}`) + const rsp = await req.arrayBuffer() + expect(uint8ArrayEquals(new Uint8Array(rsp), buf)).to.be.true() + }) })