From aafa75da84d0c1d7512f7c767e495bfdc4494a32 Mon Sep 17 00:00:00 2001 From: Alex Rickabaugh Date: Thu, 26 Oct 2017 15:14:15 -0700 Subject: [PATCH] fix(common): don't strip XSSI prefix for if error isn't JSON (#19958) This changes XhrBackend to not strip the XSSI prefix from error text if such a prefix is present but the remaining body does not parse as JSON. PR Close #19958 --- packages/common/http/src/xhr.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/common/http/src/xhr.ts b/packages/common/http/src/xhr.ts index 02ba1cb4d6..64e2a2fde6 100644 --- a/packages/common/http/src/xhr.ts +++ b/packages/common/http/src/xhr.ts @@ -181,11 +181,18 @@ 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 (req.responseType === 'json' && typeof body === 'string') { - // Attempt the parse. If it fails, a parse error should be delivered to the user. + // Save the original body, before attempting XSSI prefix stripping. + const originalBody = body; body = body.replace(XSSI_PREFIX, ''); try { + // Attempt the parse. If it fails, a parse error should be delivered to the user. body = body !== '' ? JSON.parse(body) : null; } catch (error) { + // Since the JSON.parse failed, it's reasonable to assume this might not have been a + // JSON response. Restore the original body (including any XSSI prefix) to deliver + // a better error response. + body = originalBody; + // 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) {