fetch 函数和 Request、Response 对象

122 阅读2分钟

我们平常向后端发起请求可以使用 fetch 函数,fetch 是 Web 网络请求的现代 API,旨在取代传统的 XMLHttpRequest。以下是一个基本的使用示例:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(error => {
    console.error(error)
  })

你也许不知道,fetch 除了 url,还可以用 Request 对象作为参数的详细配置;此外,我们都知道 fetch 返回的是 Promise,这个 promise 的 resolve 值是 Response 对象。

Request 对象

Request 对象包含了一个网络请求的各种信息。以下是一个用 Request 对象发起请求的例子:

// 创建 Request 对象,为请求做详细配置 
const request = new Request('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_token'
  },
  body: JSON.stringify({ key: 'value' })
});

// 用 Request 对象发起请求
fetch(request)
  .then(response => response.json())

其中,Request 的 method、headers 等请求头相关信息,可以在 fetch 函数的第二个参数中配置。

const headers = new Headers({
  'Authorization': 'Bearer your-access-token'
});

const requestOptions = {
  method: 'POST',
  headers: headers, // 指定头部
  body: JSON.stringify({ key: 'value' }) // 请求体,可以是字符串、FormData 等
};

fetch('https://api.example.com/data', requestOptions)
  .then(response => response.json())

Request 对象的其他配置属性如下表:

属性说明
methodGET、POST、PUT 等。默认为 GET请求方法
headers{ "Content-Type": "application/json" }一个对象,表示请求头部。每个属性对应一个头部字段
body字符串、Blob 对象、BufferSource、FormData、URLSearchParams 或 ReadableStream请求主体
modecors、no-cors、same-origin,默认为 cors请求的模式
credentialssame-origin、include、omit,默认为 same-origin请求的凭证模式
cachedefault、no-store、reload、no-cache,默认为 default请求的缓存模式
redirectfollow、error、manual,默认为 follow重定向处理
referrerno-referrer、client,默认为 client请求的 Referer 头部
referrerPolicyno-referrer、strict-origin-when-cross-origin,默认为 no-referrer请求的 Referrer-Policy 头部
integrity请求的完整性 ( Subresource Integrity,SRI ) 校验值用于校验响应的完整性

Response 对象

Response 对象的作用就是处理服务端返回的数据,它提供了一系列方法来处理这些数据。

fetch('https://api.example.com/data')
  .then(response => response.json()) // json 格式

fetch('https://api.example.com/data')
  .then(response => response.text()) // 文本格式

Response 对象的属性和方法:

方法描述
clone()创建并返回当前 Response 对象的一个副本。
text()返回一个 Promise,将响应体解析为文本字符串。
json()返回一个 Promise,将响应体解析为 JSON 对象。
arrayBuffer()返回一个 Promise,将响应体解析为 ArrayBuffer 对象。
blob()返回一个 Promise,将响应体解析为 Blob 对象。
formData()返回一个 Promise,将响应体解析为 FormData 对象。
ok一个布尔值,表示响应是否成功。如果状态码在 200 到 299 之间,则为 true。
status响应的 HTTP 状态码。
statusText响应的 HTTP 状态消息。
headers响应头部的 Headers 对象。

如何取消 fetch 请求

取消 fetch 请求需要用到 AbortController。

const controller = new AbortController()
const signal = controller.signal

fetch(url, { signal })

signal.addEventListener('abort',
  () => console.log('abort')
)

controller.abort() // 发出取消信号
signal.aborted // true