Skip to content

Commit

Permalink
fix: handle non-printable characters in browser responses
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
achingbrain committed Aug 14, 2020
1 parent 35f8f70 commit 71d7e3a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 <[email protected]>",
Expand Down
2 changes: 2 additions & 0 deletions src/http/fetch.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ const fetch = (url, options = {}) => {
request.upload.onprogress = options.onUploadProgress
}

request.responseType = 'arraybuffer'

return new Promise((resolve, reject) => {
/**
* @param {Event} event
Expand Down
11 changes: 11 additions & 0 deletions test/http.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down Expand Up @@ -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()
})
})

0 comments on commit 71d7e3a

Please sign in to comment.