Skip to content

Commit

Permalink
fix: handle invalid json when Content-Type=application/json (#558)
Browse files Browse the repository at this point in the history
  • Loading branch information
ddelgrosso1 authored Jul 24, 2023
1 parent b58a998 commit 71602eb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ export class Gaxios {
* @param {FetchResponse} response the HTTP response.
* @returns {Promise<any>} a promise that resolves to the response data.
*/
private getResponseDataFromContentType(
private async getResponseDataFromContentType(
response: FetchResponse
): Promise<any> {
let contentType = response.headers.get('Content-Type');
Expand All @@ -382,7 +382,13 @@ export class Gaxios {
}
contentType = contentType.toLowerCase();
if (contentType.includes('application/json')) {
return response.json();
let data = await response.text();
try {
data = JSON.parse(data);
} catch {
// continue
}
return data as {};
} else if (
contentType.includes('text/plain') ||
contentType.includes('text/html')
Expand Down
11 changes: 11 additions & 0 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,17 @@ describe('🎏 data handling', () => {
assert.deepStrictEqual(res.data, body);
});

it('should return invalid JSON as text when response Content-Type=application/json', async () => {
const body = 'hello world';
const scope = nock(url)
.get('/')
.reply(200, body, {'Content-Type': 'application/json'});
const res = await request({url});
scope.done();
assert.ok(res.data);
assert.deepStrictEqual(res.data, body);
});

it('should return text when response Content-Type=text/plain', async () => {
const body = 'hello world';
const scope = nock(url)
Expand Down

0 comments on commit 71602eb

Please sign in to comment.