Skip to content

Commit

Permalink
fix json transform when data is pre-stringified (#4020)
Browse files Browse the repository at this point in the history
  • Loading branch information
gfortaine authored Sep 6, 2021
1 parent e367be5 commit 0fc7248
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,21 @@ function getDefaultAdapter() {
return adapter;
}

function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}

return (encoder || JSON.stringify)(rawValue);
}

var defaults = {

transitional: {
Expand Down Expand Up @@ -58,7 +73,7 @@ var defaults = {
}
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
setContentTypeIfUnset(headers, 'application/json');
return JSON.stringify(data);
return stringifySafely(data);
}
return data;
}],
Expand Down
13 changes: 13 additions & 0 deletions test/specs/defaults.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ describe('defaults', function () {
expect(defaults.transformRequest[0]({foo: 'bar'})).toEqual('{"foo":"bar"}');
});

it("should also transform request json when 'Content-Type' is 'application/json'", function () {
var headers = {
'Content-Type': 'application/json',
};
expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}');
expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]');
expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"');
expect(defaults.transformRequest[0](42, headers)).toEqual('42');
expect(defaults.transformRequest[0](true, headers)).toEqual('true');
expect(defaults.transformRequest[0](false, headers)).toEqual('false');
expect(defaults.transformRequest[0](null, headers)).toEqual('null');
});

it('should do nothing to request string', function () {
expect(defaults.transformRequest[0]('foo=bar')).toEqual('foo=bar');
});
Expand Down

0 comments on commit 0fc7248

Please sign in to comment.