Skip to content

Commit dbc2713

Browse files
committed
fix: Refine response handling based on Content-Type
Refactored `DefaultResponseProcess` to intelligently handle HTTP responses: 1. Explicitly checks the 'Content-Type' header. 2. If 'text/plain', directly processes the response as text using `response.text()`. 3. For other content types, attempts to parse as JSON using `response.json()`. 4. If JSON parsing fails (e.g., the content is not valid JSON despite the header, or it's another non-JSON type like XML), the response is cloned (`response.clone()`) before reading its body as text. This correctly handles scenarios where the initial `response.json()` call has already consumed the response body stream. This approach ensures the response body is consumed only once per effective read attempt (once for text, or once for JSON attempt + once for text fallback on a cloned response if needed), resolving concerns about potential multiple reads on the original response stream and improving robustness in parsing diverse response types.
1 parent fc9c6d3 commit dbc2713

File tree

1 file changed

+13
-9
lines changed
  • console/atest-ui/src/views

1 file changed

+13
-9
lines changed

console/atest-ui/src/views/net.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,22 @@ async function DefaultResponseProcess(response: any): Promise<any> {
4141
}
4242
}
4343

44-
// Get the complete response text first
45-
const responseText = await response.text();
44+
// Check if the content type is explicitly text/plain
45+
const contentType = response.headers.get('Content-Type') || '';
46+
if (contentType.startsWith('text/plain')) {
47+
// For text/plain, directly return the text without parsing
48+
return await response.text();
49+
}
4650

47-
// Try parsing as JSON, fallback to raw text if failed
51+
// For all other types, try parsing as JSON first
4852
try {
49-
return JSON.parse(responseText);
53+
return await response.json();
5054
} catch (e) {
51-
// This is an expected case for non-JSON responses (like text/plain)
52-
// We intentionally handle this by returning the raw text
53-
// No need to log as error since this is a valid content type handling
54-
console.debug("Response is not JSON, handling as plain text");
55-
return responseText;
55+
// If JSON parsing fails, get the text content as fallback
56+
console.debug("Response is not JSON despite content type, handling as plain text");
57+
// We have to get a clone since the body stream was already consumed
58+
const clonedResponse = response.clone();
59+
return await clonedResponse.text();
5660
}
5761
}
5862

0 commit comments

Comments
 (0)