api代理提取
Interested in learning JavaScript? Get my ebook at jshandbook.com
有興趣學習JavaScript嗎? 在jshandbook.com上獲取我的電子書
Since IE5 was released in 1998, we’ve had the option to make asynchronous network calls in the browser using XMLHttpRequest (XHR).
自IE5于1998年發布以來,我們可以選擇使用XMLHttpRequest(XHR)在瀏覽器中進行異步網絡調用。
Quite a few years after this, Gmail and other rich apps made heavy use of it, and made the approach so popular that it had to have a name: AJAX.
在此之后的數年中,Gmail和其他豐富的應用程序大量使用了它,并使該方法如此流行,以至于必須使用一個名稱: AJAX 。
Working directly with the XMLHttpRequest has always been a pain, and it was almost always abstracted by some library. In particular, jQuery has its own helper functions built around it:
直接使用XMLHttpRequest一直很麻煩,并且幾乎總是被某些庫抽象化。 特別是,jQuery圍繞它構建了自己的幫助器函數:
jQuery.ajax()
jQuery.ajax()
jQuery.get()
jQuery.get()
jQuery.post()
jQuery.post()
and so on.
等等。
They had a huge impact on making asynchronous calls more accessible. In particular, they focused on older browsers to make sure everything still worked.
它們對使異步調用更易于訪問產生了巨大影響。 特別是,他們專注于較舊的瀏覽器,以確保所有功能仍然有效。
The Fetch API has been standardized as a modern approach to asynchronous network requests and uses Promises as a building block.
Fetch API已被標準化為異步網絡請求的現代方法,并使用Promises作為構建塊。
Fetch at the time of writing (Sep 2017) has a good support across the major browsers, except IE.
撰寫本文時(2017年9月)的抓取在IE之外的所有主要瀏覽器中都有很好的支持。
The polyfill released by GitHub allows us to use fetch
on any browser.
該填充工具通過GitHub的釋放使我們能夠利用fetch
的任何瀏覽器。
使用提取 (Using Fetch)
Starting to use Fetch for GET
requests is very simple:
開始將Fetch用于GET
請求非常簡單:
fetch('/file.json')
You’re already using it: fetch is going to make an HTTP request to get the file.json
resource on the same domain.
您已經在使用它:fetch將發出HTTP請求以獲取同一域上的file.json
資源。
As you can see, the fetch
function is available in the global window
scope.
如您所見, fetch
功能在全局window
范圍內可用。
Now let’s make this a bit more useful, let’s actually see what the content of the file is:
現在,讓它變得更加有用,讓我們實際看看文件的內容是什么:
fetch('./file.json') .then(response => response.json()).then(data => console.log(data))
Calling fetch()
returns a promise. We can wait for the promise to resolve by passing a handler with the then()
method of the promise.
調用fetch()
返回一個promise。 我們可以通過向處理程序傳遞promise的then()
方法來等待promise解析。
That handler receives the return value of the fetch
promise, a Response object.
該處理程序接收fetch
承諾的返回值,即Response對象。
We’ll see this object in more detail in the next section.
在下一節中,我們將更詳細地介紹該對象。
捕捉錯誤 (Catching errors)
Since fetch()
returns a promise, we can use the catch
method of the promise to intercept any error occurring during the execution of the request, and the processing is done in the then
callbacks:
由于fetch()
返回一個promise,我們可以使用promise的catch
方法來攔截在執行請求期間發生的任何錯誤, then
在then
回調中完成處理:
fetch('./file.json').then(response => { //...}.catch(err => console.error(err))
響應對象 (Response Object)
The Response Object returned by a fetch()
call contains all the information about the request and the response of the network request.
由fetch()
調用返回的響應對象包含有關請求和網絡請求響應的所有信息。
Accessing the headers
property on the response
object gives you the ability to look into the HTTP headers returned by the request:
訪問response
對象上的headers
屬性使您能夠查看請求返回的HTTP標頭:
fetch('./file.json').then(response => { console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date'))})
狀態 (status)
This property is an integer number representing the HTTP response status.
此屬性是代表HTTP響應狀態的整數。
101
,204
,205
, or304
is anull body
status101
,204
,205
,或304
是一個null body
狀態200
to299
, inclusive, is anOK
status (success)200
到299
(含)之間為OK
狀態(成功)301
,302
,303
,307
, or308
is aredirect
301
,302
,303
,307
,或308
是一個redirect
fetch('./file.json') .then((response) => { console.log(response.status) })
statusText (statusText)
statusText
is a property representing the status message of the response. If the request is successful, the status is OK
.
statusText
是代表響應狀態消息的屬性。 如果請求成功,則狀態為OK
。
fetch('./file.json') .then(response => console.log(response.statusText))
網址 (url)
url
represents the full URL of the property that we fetched.
url
代表我們獲取的屬性的完整URL。
fetch('./file.json') .then(response => console.log(response.url))
身體內容 (Body content)
A response has a body, accessible using the text()
or json()
methods, which return a promise.
響應具有一個正文,可以使用text()
或json()
方法訪問該text()
,并返回一個Promise。
fetch('./file.json').then(response => response.text()).then(body => console.log(body))
fetch('./file.json').then(response => response.json()).then(body => console.log(body))
The same can be written using the ES2017 async functions:
可以使用ES2017 異步函數編寫相同的代碼 :
(async () => { const response = await fetch('./file.json') const data = await response.json() console.log(data)})()
請求對象 (Request Object)
The Request object represents a resource request, and it’s usually created using the new Request()
API.
Request對象代表資源請求,通常使用new Request()
API創建。
Example:
例:
const req = new Request('/api/todos')
The Request object offers several read-only properties to inspect the resource request details, including
Request對象提供了幾個只讀屬性來檢查資源請求的詳細信息,包括
method
: the request’s method (GET, POST, etc.)method
:請求的方法(GET,POST等)url
: the URL of the request.url
:請求的URL。headers
: the associated Headers object of the requestheaders
:請求的關聯Headers對象referrer
: the referrer of the requestreferrer
:請求的推薦人cache
: the cache mode of the request (e.g., default, reload, no-cache).cache
:請求的緩存模式(例如,默認,重新加載,無緩存)。
And exposes several methods including json()
, text()
and formData()
to process the body of the request.
并且公開了幾種方法,包括json()
, text()
和formData()
來處理請求的正文。
The full API can be found here.
完整的API可以在這里找到。
Being able to set the HTTP request header is essential, and fetch
gives us the ability to do this using the Headers object:
能夠設置HTTP請求標頭至關重要, fetch
使我們能夠使用Headers對象執行此操作:
const headers = new Headers()headers.append('Content-Type', 'application/json')
or, simpler:
或者,更簡單:
const headers = new Headers({ 'Content-Type': 'application/json' })
To attach the headers to the request, we use the Request object, and pass it to fetch()
instead of simply passing the URL.
要將標頭附加到請求,我們使用Request對象,然后將其傳遞給fetch()
而不是簡單地傳遞URL。
Instead of:
代替:
fetch('./file.json')
we do
我們的確是
const request = new Request('./file.json', { headers: new Headers({ 'Content-Type': 'application/json' }) })
fetch(request)
The Headers object is not limited to setting values, but we can also query it:
Headers對象不僅限于設置值,我們還可以查詢它:
headers.has('Content-Type') headers.get('Content-Type')
and we can delete a header that was previously set:
我們可以刪除先前設置的標頭:
headers.delete('X-My-Custom-Header')
POST請求 (POST Requests)
Fetch also allows you to use any other HTTP method in your request: POST, PUT, DELETE or OPTIONS.
提取還允許您在請求中使用任何其他HTTP方法:POST,PUT,DELETE或OPTIONS。
Specify the method in the method property of the request, and pass additional parameters in the header and in the request body:
在請求的method屬性中指定方法,并在標頭和請求正文中傳遞其他參數:
Example of a POST request:
POST請求的示例:
const options = { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: 'foo=bar&test=1' }
fetch(url, options) .catch((err) => { console.error('Request failed', err) })
如何取消獲取請求 (How to cancel a fetch request)
For a few years after fetch
was introduced, there was no way to abort a request once opened.
引入fetch
后的幾年,一旦打開請求就無法中止請求。
Now we can, thanks to the introduction of AbortController
and AbortSignal
, a generic API to notify abort events
現在,由于引入了AbortController
和AbortSignal
(用于通知中止事件的通用API),我們可以
You integrate this API by passing a signal as a fetch parameter:
您可以通過傳遞信號作為訪存參數來集成此API:
const controller = new AbortController()const signal = controller.signalfetch(‘./file.json’, { signal })
You can set a timeout that fires an abort event 5 seconds after the fetch request has started, to cancel it:
您可以設置一個超時,以在獲取請求開始后5秒鐘觸發中止事件,以將其取消:
setTimeout(() => controller.abort(), 5 * 1000)
Conveniently, if the fetch already returned, calling abort()
won’t cause any error.
方便的是,如果獲取操作已經返回,則調用abort()
不會導致任何錯誤。
When an abort signal occurs, fetch will reject the promise with a DOMException
named AbortError
:
當發生異常中止信號時,訪AbortError
將使用名為AbortError
的DOMException
拒絕諾言:
fetch('./file.json', { signal }).then(response => response.text()).then(text => console.log(text)).catch(err => { if (err.name === 'AbortError') { console.error('Fetch aborted') } else { console.error('Another error', err) }})
Interested in learning JavaScript? Get my ebook at jshandbook.com
有興趣學習JavaScript嗎? 在jshandbook.com上獲取我的電子書
翻譯自: https://www.freecodecamp.org/news/understanding-the-fetch-api-a7d4c08c2a7/
api代理提取