whatwg-fetch 解析(下)

784 阅读2分钟

Response

response 不是手动构造的,可以作为 promise 回调中 resolved 的参数。

属性

  • status(number): HTTP 响应码的范围为 100~599
  • statusText(string):服务器返回的状态文本
  • ok(boolean):如果状态码是 2xx 返回 true
  • headers
  • url(string)

方法

方法返回的是 promise,关联数据准备好后才可以被解析出来

  • text(): 得到字符串文本
  • json(): 得到 JSON 对象
  • blob(): 得到二进制 Blob 对象
  • arrayBuffer(): 得到 FormData 表单对象
  • formData(): 得到二进制 ArrayBuffer 对象

Headers

Headers 代表一系列请求响应头,它是大小写敏感的,可以通过名字找到对应的 header,单个 header 会合并多个值。

  • has(name)(boolean): 判断是否有这个 header
  • get(name)(string): 获取对应的 header
  • set(name,value): 设置一个 header 的 name 和 value
  • append(name,value): 增加一个 header
  • delete(name): 删除 header
  • forEach(function(value,name){...},[thisContext]): 遍历一个 header
<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch@3.6.2/dist/fetch.umd.min.js"></script>
<script>
  fetch("http://localhost:3000/test", {
    method: "POST",
    body: JSON.stringify({ name: "leon" }),
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "same-origin",
  }).then(
    async function (response) {
      console.log("🚀 ~ file: whatwg-fetch.html:12 ~ response:", response.headers.get("Content-Type")); // text/html; charset=utf-8
    },
    function (error) {
      console.log(error.message);
    }
  );
</script>

响应的时候可以通过 get 方法获取 Content-Type 的内容。

Error

如果网络出现网络错误,或者其他原因导致网络请求出错,fetch() 会返回 error。

如果出现4xx或者5xx这样的错误不会 rejected,只有2xx才会resolved,可以根据 response.status 返回的值进行额外处理。

警告

whatwg-fetch 不能完整实现 WHATWG Fetch standard,因为一些细节没有必要实现或者是无法实现的。包括不能实现重定向,不能改变缓存指令,无法禁用同源 cookie。

小结

fetch API 由 WHATWG 组织制定与维护,为了实现更好的兼容性,出现了 whatwg-fetch,他是 fetch API 的 polyfill。本篇文章介绍了 response,headers,error 和警告,从警告中可以看出 whatwg-fetch 还有很多需要完善的地方,实际项目中需要完善代码实现对应的能力。

参考资料:github.github.io/fetch/