Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix json transform when data is pre-stringified #4020

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion lib/defaults.js
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
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