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 状态码(404、504,等)而被拒绝。因此,then() 处理器必须检查 Response.ok 和/或 Response.status 属性。
fetch() 方法由内容安全策略的 connect-src 指令(而不是它查询的资源的指令)控制。
备注:
fetch() 方法的参数与 Request() 构造函数是一样的。
语法
fetch(resource)
fetch(resource, options)
参数
resource-
定义你想要获取的资源。可以是:
- 一个字符串或任何其他具有字符串化器的对象(包括
URL对象),提供你想要获取的资源的 URL。URL 可以是相对于基础 URL 的,基础 URL 是窗口上下文中文档的baseURI或者 worker 上下文中的WorkerGlobalScope.location。 - 一个
Request对象。
- 一个字符串或任何其他具有字符串化器的对象(包括
options可选-
一个包含你想要应用到请求上的任何自定义设置的
RequestInit对象。
返回值
异常
AbortErrorDOMException-
请求被
AbortController的abort()方法调用所终止。 NotAllowedErrorDOMException-
如果 Topics API 的使用被
browsing-topics权限策略明确禁止,且fetch()请求中包含browsingTopics: true,则会抛出此异常。 TypeError-
可以由以下原因引起:
| 原因 | 失败的示例 |
|---|---|
| 被权限策略阻止 | Attribution Reporting API 的使用被 attribution-reporting Permissions-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' });
|
无效的模式(navigate 和 websocket)。 |
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',而请求体不是 null 或 undefined。
|
fetch('https://example.com/', {
method: 'GET',
body: new FormData(),
});
|
| 如果 fetch 抛出了网络错误。 |
示例
在 Fetch 请求示例(查看 Fetch 请求在线示例)中,我们使用对应的构造函数创建了一个新的 Request 对象,然后调用 fetch() 获取资源。因为我们是在请求一个图片,为了解析正常,我们对响应执行 Body.blob 来设置相应的 MIME 类型。然后创建一个 Object URL,并在 <img> 元素中把它显示出来。
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 值来指示我们可以接受什么类型的缓存响应:
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 构造函数,来实现同样的效果:
const req = new Request("flowers.jpg", options);
init 对象中的 headers 也可以是一个对象字面量:
const options = {
headers: {
"Cache-Control": "max-age=60480",
},
};
const req = new Request("flowers.jpg", options);
规范
| Specification |
|---|
| Fetch> # fetch-method> |
浏览器兼容性
Loading…