Skip to content

Commit

Permalink
Fixing response with utf-8 BOM can not parse to json (#2419)
Browse files Browse the repository at this point in the history
* fix: remove byte order marker (UTF-8 BOM) when transform response

* fix: remove BOM only utf-8

* test: utf-8 BOM

* fix: incorrect param name

Co-authored-by: Jay <jasonsaayman@gmail.com>
  • Loading branch information
a631807682 and jasonsaayman committed Jul 1, 2020
1 parent c4300a8 commit 16aa2ce
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/adapters/http.js
Expand Up @@ -235,6 +235,9 @@ module.exports = function httpAdapter(config) {
var responseData = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString(config.responseEncoding);
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
}

response.data = responseData;
Expand Down
16 changes: 15 additions & 1 deletion lib/utils.js
Expand Up @@ -312,6 +312,19 @@ function extend(a, b, thisArg) {
return a;
}

/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}

module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
Expand All @@ -333,5 +346,6 @@ module.exports = {
forEach: forEach,
merge: merge,
extend: extend,
trim: trim
trim: trim,
stripBOM: stripBOM
};
20 changes: 20 additions & 0 deletions test/unit/adapters/http.js
Expand Up @@ -74,6 +74,26 @@ describe('supports http with nodejs', function () {
});
});

it('should allow passing JSON with BOM', function (done) {
var data = {
firstName: 'Fred',
lastName: 'Flintstone',
emailAddr: 'fred@example.com'
};

server = http.createServer(function (req, res) {
res.setHeader('Content-Type', 'application/json;charset=utf-8');
var bomBuffer = Buffer.from([0xEF, 0xBB, 0xBF])
var jsonBuffer = Buffer.from(JSON.stringify(data));
res.end(Buffer.concat([bomBuffer, jsonBuffer]));
}).listen(4444, function () {
axios.get('http://localhost:4444/').then(function (res) {
assert.deepEqual(res.data, data);
done();
});
});
});

it('should redirect', function (done) {
var str = 'test response';

Expand Down

0 comments on commit 16aa2ce

Please sign in to comment.