Fetch API 簡介

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

Fetch API 爲獲取網絡資源提供了對應的接口。它與廣泛使用的XMLHttpRequest類似,但新的API提供了更強大的功能和靈活的配置。


概念及使用

Fetch provides a generic definition of Request and Response objects (and other things involved with network requests). This will allow them to be used wherever they are needed in the future, whether it’s for service workers, Cache API and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your own responses programmatically.

Fetch提供了一種針對Request和Response(也就是所謂的請求-響應模型)方式的通用定義。(也就是做了抽象定義)這使得他們可以在將來任何時候被使用,不管是service worker,Cache API 或是其他類似處理請求和響應的事物。更有甚者,未來你可以手動定義你自己的響應模型。

It also provides a definition for related concepts such as CORS and the HTTP origin header semantics, supplanting their separate definitions elsewhere.

對於包括CORS和HTTP同源策略等相關概念,也同樣提供了定義,這裏的定義將取代其他地方的類似定義。(也就是說,一切以fetch的定義爲準)

For making a request and fetching a resource, use the GlobalFetch.fetch method. It is implemented in multiple interfaces, specifically Window and WorkerGlobalScope. This makes it available in pretty much any context you might want to fetch resources in.

爲了生成一個請求,可以使用GlobalFetch.fetch方法。這已經被多個接口實現了,尤其是Window和WorkerGlobalScope。這就可以讓你在任何想要獲取資源的地方和情境下使用fetch。

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request).

fetch()方法需要一個強制的參數-path(你要獲取的資源url路徑)。同時fetch返回一個Promise,將response 作爲resolve的返回值(無論請求是否成功都會返回),你可以接着傳遞初始化設置對象作爲第二個參數。

Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled (see Body).

一旦Response想要收到了,緊接着就會觸發一系列的方法,例如定義body的內容,或是結果如何被處理。

You can create a request and response directly using the Request() and Response() constructors, but you are unlikely to do this directly. Instead, these are more likely to be created as results of other API actions (for example, FetchEvent.respondWith from service workers).

你可以手動創建一個request或是response通過Request()方法和Response()方法。一般來說你很少會手動生成這個,更多的情況下是作爲其他API的結果。(舉個例子,來自service workers的FetchEvent.respondWith)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章