处理获取响应 - JS
Processing fetch response - JS
我在 fetch
的 GET 请求后得到了响应。我知道这个响应将 return 一个数组。当我用 .json()
处理它时 - 一切都很好。但是,当我尝试使用 .formData()
处理相同的响应时,它失败了。
这是代码:
fetch(fullPath)
.then(response => response.json())
.then((allData) => {
console.log(allData);
})
.catch((e) => console.log(e));
与 response.formData()
相同的那个不起作用。
所以问题是 - 如果 off. doc says 和 formData()
也是从响应?
如果响应不具有 multipart/form-data 类型,formData()
方法将 return 出错。它应该有 key=value
个条目。请参阅 this question 有人询问如何使用该格式设计响应。
如果您对无效的响应调用 json()
方法,也会发生类似的情况 JSON:这也会触发异常。
由于multipart/form-data
很少用作响应内容类型,所以formData()
方法也不经常使用。 documentation on MDN 提到它对服务人员有一些用处:
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).
我在 fetch
的 GET 请求后得到了响应。我知道这个响应将 return 一个数组。当我用 .json()
处理它时 - 一切都很好。但是,当我尝试使用 .formData()
处理相同的响应时,它失败了。
这是代码:
fetch(fullPath)
.then(response => response.json())
.then((allData) => {
console.log(allData);
})
.catch((e) => console.log(e));
与 response.formData()
相同的那个不起作用。
所以问题是 - 如果 off. doc says 和 formData()
也是从响应?
如果响应不具有 multipart/form-data 类型,formData()
方法将 return 出错。它应该有 key=value
个条目。请参阅 this question 有人询问如何使用该格式设计响应。
如果您对无效的响应调用 json()
方法,也会发生类似的情况 JSON:这也会触发异常。
由于multipart/form-data
很少用作响应内容类型,所以formData()
方法也不经常使用。 documentation on MDN 提到它对服务人员有一些用处:
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).