WordPress/gutenberg

apiFetch should be able to handle a 200 response code with an empty body

Open

#21,899 opened on Apr 26, 2020

View on GitHub
 (13 comments) (0 reactions) (1 assignee)JavaScript (3,893 forks)batch import
Good First IssueNeeds DevREST API Interaction[Package] API fetch[Status] In Progress[Type] Enhancement

Repository metrics

Stars
 (9,607 stars)
PR merge metrics
 (Avg merge 12d 18h) (509 merged PRs in 30d)

Description

Describe the bug If the response is 200 but the body is empty, it causes an error: image

The code handles 204 responses, but not 200 with empty body: https://github.com/WordPress/gutenberg/blob/%40wordpress/api-fetch%403.13.1/packages/api-fetch/src/utils/response.js#L16-L20

From https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

The common use case is to return 204 as a result of a PUT request, updating a resource, without changing the current content of the page displayed to the user. If the resource is created, 201 Created is returned instead. If the page should be changed to the newly updated page, the 200 should be used instead.

So, since a 200 with empty body isn't a wrong response, the apiFetch should handle it instead of throwing a try/catch error.

https://mcculloughwebservices.com/2016/09/23/handling-a-null-response-from-an-api/ might be helpful.

Contributor guide