sh00ter
sh00ter

Reputation: 35

Processing fetch response - JS

I have the response after GET-request with fetch. I know that this response will return an Array. When I process it with .json() - everything is fine. But when I try to process same response with .formData()- it fails. Here's the code:

fetch(fullPath)
    .then(response => response.json())
    .then((allData) => {
      console.log(allData);
    })
    .catch((e) => console.log(e));

same one with response.formData() doesn't work. So the question is - why we are not able to process the promise in first "then" with .formData() if the off. doc says that formData() is also acceptable method for extracting a body from the response ?

Upvotes: 2

Views: 381

Answers (1)

trincot
trincot

Reputation: 350841

The formData() method will return an error if the response is not having the multipart/form-data type. It should have key=value entries. See this question where someone asks about designing a response with that format.

Something similar happens if you call the json() method on a response that is not valid JSON: that also triggers an exception.

Since multipart/form-data is rarely used as response content type, the formData() method is not often used either. The documentation on MDN mentions it has some use for service workers:

Note: This [method] is mainly relevant to service workers. If a user submits a form and a service worker intercepts the request, you could for example call formData() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally).

Upvotes: 3

Related Questions