2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-05 16:42:32 +03:00

fix: silentJSONParsing=false should throw on invalid JSON (#7253) (#7257)

Co-authored-by: Rudransh Gupta <rudranshgupta@Rudranshs-MacBook-Pro.local>
Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
Rudransh
2025-12-06 14:15:54 +05:30
committed by GitHub
parent ec9d94e9f8
commit 7d19335e43
2 changed files with 71 additions and 2 deletions
+2 -2
View File
@@ -108,7 +108,7 @@ const defaults = {
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
const strictJSONParsing = !silentJSONParsing;
try {
return JSON.parse(data, this.parseReviver);
@@ -158,4 +158,4 @@ utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
defaults.headers[method] = {};
});
export default defaults;
export default defaults;
+69
View File
@@ -0,0 +1,69 @@
import assert from 'assert';
import axios from '../index.js';
describe('Regression: Silent JSON Parsing', function () {
beforeEach(function () {
// Mock adapter to return invalid JSON
axios.defaults.adapter = async (config) => {
return {
data: '{ invalid json }',
status: 200,
statusText: 'OK',
headers: {},
config
};
};
});
afterEach(function () {
delete axios.defaults.adapter;
});
it('should throw SyntaxError when silentJSONParsing is false', async function () {
try {
await axios.get('/test', {
transitional: {
silentJSONParsing: false
}
});
assert.fail('Should have thrown error');
} catch (err) {
assert.ok(err.name === 'SyntaxError' || err.code === 'ERR_BAD_RESPONSE', 'Error should be SyntaxError or ERR_BAD_RESPONSE');
}
});
it('should return raw string when silentJSONParsing is true (default)', async function () {
const response = await axios.get('/test', {
transitional: {
silentJSONParsing: true
}
});
assert.strictEqual(response.data, '{ invalid json }');
});
it('should throw SyntaxError when responseType is json (legacy behavior)', async function () {
try {
await axios.get('/test', {
responseType: 'json',
transitional: {
silentJSONParsing: false
}
});
assert.fail('Should have thrown error');
} catch (err) {
assert.ok(err.name === 'SyntaxError' || err.code === 'ERR_BAD_RESPONSE', 'Error should be SyntaxError or ERR_BAD_RESPONSE');
}
});
it('should swallow error when silentJSONParsing is true and responseType is json (legacy behavior)', async function () {
const response = await axios.get('/test', {
responseType: 'json',
transitional: {
silentJSONParsing: true
}
});
assert.strictEqual(response.data, '{ invalid json }');
});
});