Skip to content

Commit

Permalink
fix json transform when data is pre-stringified
Browse files Browse the repository at this point in the history
  • Loading branch information
gfortaine committed Sep 6, 2021
1 parent 4f25380 commit 32e9c6d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/defaults.js
Expand Up @@ -58,6 +58,14 @@ var defaults = {
}
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
setContentTypeIfUnset(headers, 'application/json');
if (utils.isString(data)) {
try {
JSON.parse(data);
return data;
} catch (e) {
return JSON.stringify(data);
}
}
return JSON.stringify(data);
}
return data;
Expand Down
12 changes: 12 additions & 0 deletions test/specs/defaults.spec.js
Expand Up @@ -20,6 +20,18 @@ 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 () {
expect(defaults.transformRequest[0](42, {
'Content-Type': 'application/json'
})).toEqual('42');
expect(defaults.transformRequest[0]('bar', {
'Content-Type': 'application/json'
})).toEqual('"bar"');
expect(defaults.transformRequest[0](JSON.stringify({foo: 'bar'}), {
'Content-Type': 'application/json'
})).toEqual('{"foo":"bar"}');
});

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

0 comments on commit 32e9c6d

Please sign in to comment.