WorkerOrGlobalScope.fetch()

翻译不完整。 请帮助我们翻译这篇文章!

位于 WorkerOrGlobalScope 这一个 mixin 中的 fetch() 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response 对象。

WindowWorkerGlobalScope 都实现了 WorkerOrGlobalScope。 ——这意味着基本在任何场景下只要你想获取资源,都可以使用 位于 WorkerOrGlobalScope 中的 fetch() 方法。

当遇到网络错误时,fetch() 返回的 promise 会被 reject,并传回 TypeError,虽然这也可能因为权限或其它问题导致。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 Response.ok 属性为 true。HTTP 404 状态并不被认为是网络错误。

fetch() 方法由 Content Security Policy 的 connect-src指令控制,而不是它请求的资源。

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

语法

Promise<Response> fetch(input[, init]);

参数

?input
定义要获取的资源。这可能是:
  • 一个 USVString 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data: 作为 schemes.
  • 一个 Request 对象。
init 可选
一个配置项对象,包括所有对请求的设置。可选的参数有:
  • method: 请求使用的方法,如 GETPOST。
  • headers: 请求的头信息,形式为 Headers 的对象或包含 ByteString 值的对象字面量。
  • body: 请求的 body 信息:可能是一个 BlobBufferSourceFormDataURLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 FederatedCredential 实例或是一个 PasswordCredential 实例。
  • cache:  请求的 cache 模式: default、 no-storereload 、 no-cache 、 force-cache 或者 only-if-cached
  • redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中默认使用follow(Chrome 47之前的默认值是manual)。
  • referrer: 一个 USVString 可以是 no-referrerclient或一个 URL。默认是 client。
  • referrerPolicy: 指定了HTTP头部referer字段的值。可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
  • integrity: 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。

返回值

一个 Promise,resolve 时回传 Response 对象。

例外

类型 描述
AbortError 请求被AbortController.abort()终止。
TypeError Firefox 43开始,如果fetch()接收到含有用户名和密码的URL(例如http://user:password@example.com),它将会抛出一个TypeError

示例

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

var myImage = document.querySelector('img');

var myRequest = new Request('flowers.jpg');

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(response) {
  var objectURL = URL.createObjectURL(response);
  myImage.src = objectURL;
});

在 Fetch with init then Request 示例 (参见 Fetch Request init live) 中,我们做同样的操作,除了在调用 fetch() 时传入一个 init 对象:

var myImage = document.querySelector('img');

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg');

fetch(myRequest,myInit).then(function(response) {
  ... 
});

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

var myRequest = new Request('flowers.jpg',myInit);

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

var myInit = { method: 'GET',
               headers: {
                   'Content-Type': 'image/jpeg'
               },
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

规范

Specification Status Comment
Fetch
fetch()
Living Standard Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
Fetch
fetch()
Living Standard Initial definition
Credential Management Level 1 Working Draft Adds FederatedCredential or PasswordCredential instance as a possible value for init.credentials.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
fetch
Experimental
Chrome Full support 42Edge Full support 14Firefox Full support 39
Full support 39
Full support 34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enable preference. To change preferences in Firefox, visit about:config.
Full support 52
Notes
Notes fetch() now defined on WindowOrWorkerGlobalScope mixin.
IE No support NoOpera Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari Full support 10.1WebView Android Full support 42Chrome Android Full support 42Firefox Android Full support 39
Full support 39
Full support 34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enable preference. To change preferences in Firefox, visit about:config.
Full support 52
Notes
Notes fetch() now defined on WindowOrWorkerGlobalScope mixin.
Opera Android Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari iOS Full support 10.3Samsung Internet Android Full support 4.0
Support for blob: and data:
Experimental
Chrome Full support 48Edge Full support 79Firefox ? IE No support NoOpera ? Safari ? WebView Android Full support 43Chrome Android Full support 48Firefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android Full support 5.0
referrerPolicyChrome Full support 52Edge Full support 79Firefox Full support 52IE No support NoOpera Full support 39Safari Full support 11.1WebView Android Full support 52Chrome Android Full support 52Firefox Android Full support 52Opera Android Full support 41Safari iOS No support NoSamsung Internet Android Full support 6.0
signal
Experimental
Chrome Full support 66Edge Full support 16Firefox Full support 57IE No support NoOpera Full support 53Safari Full support 11.1WebView Android Full support 66Chrome Android Full support 66Firefox Android Full support 57Opera Android Full support 47Safari iOS Full support 11.3Samsung Internet Android Full support 9.0
Streaming response body
Experimental
Chrome Full support 43Edge Full support 14Firefox Full support Yes
Disabled
Full support Yes
Disabled
Disabled This feature is behind the dom.streams.enabled preference and the javascript.options.streams preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 29Safari Full support 10.1WebView Android Full support 43Chrome Android Full support 43Firefox Android No support NoOpera Android No support NoSafari iOS Full support 10.3Samsung Internet Android Full support 4.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接