Skip to content

Commit 0fc7248

Browse files
authored
fix json transform when data is pre-stringified (#4020)
1 parent e367be5 commit 0fc7248

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Diff for: lib/defaults.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,21 @@ function getDefaultAdapter() {
2626
return adapter;
2727
}
2828

29+
function stringifySafely(rawValue, parser, encoder) {
30+
if (utils.isString(rawValue)) {
31+
try {
32+
(parser || JSON.parse)(rawValue);
33+
return utils.trim(rawValue);
34+
} catch (e) {
35+
if (e.name !== 'SyntaxError') {
36+
throw e;
37+
}
38+
}
39+
}
40+
41+
return (encoder || JSON.stringify)(rawValue);
42+
}
43+
2944
var defaults = {
3045

3146
transitional: {
@@ -58,7 +73,7 @@ var defaults = {
5873
}
5974
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
6075
setContentTypeIfUnset(headers, 'application/json');
61-
return JSON.stringify(data);
76+
return stringifySafely(data);
6277
}
6378
return data;
6479
}],

Diff for: test/specs/defaults.spec.js

+13
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ describe('defaults', function () {
2020
expect(defaults.transformRequest[0]({foo: 'bar'})).toEqual('{"foo":"bar"}');
2121
});
2222

23+
it("should also transform request json when 'Content-Type' is 'application/json'", function () {
24+
var headers = {
25+
'Content-Type': 'application/json',
26+
};
27+
expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}');
28+
expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]');
29+
expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"');
30+
expect(defaults.transformRequest[0](42, headers)).toEqual('42');
31+
expect(defaults.transformRequest[0](true, headers)).toEqual('true');
32+
expect(defaults.transformRequest[0](false, headers)).toEqual('false');
33+
expect(defaults.transformRequest[0](null, headers)).toEqual('null');
34+
});
35+
2336
it('should do nothing to request string', function () {
2437
expect(defaults.transformRequest[0]('foo=bar')).toEqual('foo=bar');
2538
});

0 commit comments

Comments
 (0)