Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. Window
  4. Window:fetch() 方法

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Window:fetch() 方法

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年3月.

* Some parts of this feature may have varying levels of support.

Window 接口的fetch() 方法用于发起获取资源的请求,它会返回一个会在请求响应后兑现的 promise。

该 promise 会兑现一个表示请求响应的Response 对象。

当请求失败(例如,因为请求 URL 的格式错误或网络错误)时,fetch() 的 promise 才会被拒绝。fetch() 的 promise不会因为服务器响应表示错误的 HTTP 状态码(404504,等)而被拒绝。因此,then() 处理器必须检查Response.ok 和/或Response.status 属性。

fetch() 方法由内容安全策略connect-src 指令(而不是它查询的资源的指令)控制。

备注:fetch() 方法的参数与Request() 构造函数是一样的。

语法

js
fetch(resource)fetch(resource, options)

参数

resource

定义你想要获取的资源。可以是:

  • 一个字符串或任何其他具有字符串化器的对象(包括URL 对象),提供你想要获取的资源的 URL。URL 可以是相对于基础 URL 的,基础 URL 是窗口上下文中文档的baseURI 或者 worker 上下文中的WorkerGlobalScope.location
  • 一个Request 对象。
options可选

一个包含你想要应用到请求上的任何自定义设置的RequestInit 对象。

返回值

一个Promise,会兑现Response 对象。

异常

AbortErrorDOMException

请求被AbortControllerabort() 方法调用所终止。

NotAllowedErrorDOMException

如果Topics API 的使用被browsing-topics权限策略明确禁止,且fetch() 请求中包含browsingTopics: true,则会抛出此异常。

TypeError

可以由以下原因引起:

原因失败的示例
被权限策略阻止Attribution Reporting API 的使用被attribution-reportingPermissions-Policy 所阻止,而fetch() 请求又指定了attributionReporting
无效的标头名称。
// “C ontent-Type”中的空格const headers = {  'C ontent-Type': 'text/xml',  'Breaking-Bad': '<3',};fetch('https://example.com/', { headers });
无效的标头值。标头对象必须明确包含两个元素。
const headers = [  ['Content-Type', 'text/html', 'extra'],  ['Accept'],];fetch('https://example.com/', { headers });
无效的 URL 或方案(scheme),或使用 fetch 不支持的方案,或使用不支持特定请求模式的方案。
fetch('blob://example.com/', { mode: 'cors' });
URL 中包含凭据。
fetch('https://user:password@example.com/');
无效的来源(referrer)URL。
fetch('https://example.com/', { referrer: './abc\u0000df' });
无效的模式(navigatewebsocket)。
fetch('https://example.com/', { mode: 'navigate' });
如果请求的缓存模式是“only-if-cached”,而请求模式不是“same-origin”。
fetch('https://example.com/', {  cache: 'only-if-cached',  mode: 'no-cors',});
如果请求方法是无效的名称标记或被禁止的标头之一('CONNECT''TRACE''TRACK')。
fetch('https://example.com/', { method: 'CONNECT' });
如果请求的模式是“no-cors”,而请求方法不是列入 CORS 白名单的方法('GET''HEAD''POST')。
fetch('https://example.com/', {  method: 'CONNECT',  mode: 'no-cors',});
如果请求方法是'GET''HEAD',而请求体不是nullundefined
fetch('https://example.com/', {  method: 'GET',  body: new FormData(),});
如果 fetch 抛出了网络错误。

示例

Fetch 请求示例(查看Fetch 请求在线示例)中,我们使用对应的构造函数创建了一个新的Request 对象,然后调用fetch() 获取资源。因为我们是在请求一个图片,为了解析正常,我们对响应执行Body.blob 来设置相应的 MIME 类型。然后创建一个 Object URL,并在<img> 元素中把它显示出来。

js
const myImage = document.querySelector("img");const myRequest = new Request("flowers.jpg");window  .fetch(myRequest)  .then((response) => {    if (!response.ok) {      throw new Error(`HTTP 错误!状态:${response.status}`);    }    return response.blob();  })  .then((response) => {    myImage.src = URL.createObjectURL(response);  });

带有初始化的 Fetch 请求示例(查看带有初始化的 Fetch 请求在线示例)中,我们做同样的操作,除了在调用fetch() 时传入了options 对象。在本例中,我们可以设置Cache-Control 值来指示我们可以接受什么类型的缓存响应:

js
const myImage = document.querySelector("img");const reqHeaders = new Headers();// 除非缓存的响应超过一周,否则都可以接受reqHeaders.set("Cache-Control", "max-age=604800");const options = {  headers: reqHeaders,};// 将带有标头的“options”对象作为 init 来传递。const req = new Request("flowers.jpg", options);fetch(req).then((response) => {  // ...});

你也可以传入同样的init 对象到Request 构造函数,来实现同样的效果:

js
const req = new Request("flowers.jpg", options);

init 对象中的headers 也可以是一个对象字面量:

js
const options = {  headers: {    "Cache-Control": "max-age=60480",  },};const req = new Request("flowers.jpg", options);

规范

Specification
Fetch
# fetch-method

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp