fix(common): treat an empty body as null when parsing JSON in HttpClient (#19958)
Previously, XhrBackend would call JSON.parse('') if the response body was empty (a 200 status code with content-length 0). This changes the XhrBackend to attempt the JSON parse only if the response body is non-empty. Otherwise, the body is left as null. Fixes #18680. Fixes #19413. Fixes #19502. Fixes #19555. PR Close #19958
This commit is contained in:

committed by
Miško Hevery

parent
eb01ad583f
commit
503be69af6
@ -180,24 +180,20 @@ export class HttpXhrBackend implements HttpBackend {
|
||||
|
||||
// Check whether the body needs to be parsed as JSON (in many cases the browser
|
||||
// will have done that already).
|
||||
if (ok && req.responseType === 'json' && typeof body === 'string') {
|
||||
if (req.responseType === 'json' && typeof body === 'string') {
|
||||
// Attempt the parse. If it fails, a parse error should be delivered to the user.
|
||||
body = body.replace(XSSI_PREFIX, '');
|
||||
try {
|
||||
body = JSON.parse(body);
|
||||
body = body !== '' ? JSON.parse(body) : null;
|
||||
} catch (error) {
|
||||
// Even though the response status was 2xx, this is still an error.
|
||||
ok = false;
|
||||
// The parse error contains the text of the body that failed to parse.
|
||||
body = { error, text: body } as HttpJsonParseError;
|
||||
}
|
||||
} else if (!ok && req.responseType === 'json' && typeof body === 'string') {
|
||||
try {
|
||||
// Attempt to parse the body as JSON.
|
||||
body = JSON.parse(body);
|
||||
} catch (error) {
|
||||
// Cannot be certain that the body was meant to be parsed as JSON.
|
||||
// Leave the body as a string.
|
||||
// If this was an error request to begin with, leave it as a string, it probably
|
||||
// just isn't JSON. Otherwise, deliver the parsing error to the user.
|
||||
if (ok) {
|
||||
// Even though the response status was 2xx, this is still an error.
|
||||
ok = false;
|
||||
// The parse error contains the text of the body that failed to parse.
|
||||
body = { error, text: body } as HttpJsonParseError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user