2

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 ?

sh00ter
  • 35
  • 3
  • Interesting. Indeed the docs say `.formData` can be used in both request and response but the only examples in the docs are for requests. – stever Jan 26 '19 at 20:35

1 Answers1

3

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).

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank's a lot for U'r answer !. I assumed that there is some kind of types mismatch but now I know it clearly. But I also want to clarify one moment: why can't we consider an Array obj that comes in a response as the range of `key=value` entries ? – sh00ter Jan 26 '19 at 22:32
  • 1
    I'm not sure what you mean, but form-data type is a specific format. If the response data is not according to that format, but is (for instance) formatted as JSON, XML, or CSV, then the `formData()` method will not work, even when the data is really representing some array. It is the format in which that array is returned that determines with which method you can read it. – trincot Jan 27 '19 at 10:00
  • I'm sorry for the definitions that are, perhaps, wrong or not clearly enough - it's just a lack of practical experience. Thank U very much for Ur explanations. – sh00ter Jan 27 '19 at 11:17