api代理提取_了解提取API

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方法來攔截在執行請求期間發生的任何錯誤, thenthen回調中完成處理:

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, or 304 is a null body status

    101204205 ,或304是一個null body狀態

  • 200 to 299, inclusive, is an OK status (success)

    200299 (含)之間為OK狀態(成功)

  • 301, 302, 303, 307, or 308 is a redirect

    301302303307 ,或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 request

    headers :請求的關聯Headers對象

  • referrer: the referrer of the request

    referrer :請求的推薦人

  • 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

現在,由于引入了AbortControllerAbortSignal (用于通知中止事件的通用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將使用名為AbortErrorDOMException拒絕諾言:

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代理提取

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394727.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394727.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394727.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

react.lazy 路由懶加載_React lazy/Suspense使用及源碼解析

React v16.6.0已經發布快一年了,為保障項目迭代發布,沒有及時更新react版本,最近由于開啟了新項目,于是使用新的react版本進行了項目開發。項目工程如何搭建,如何滿足兼容性要求,如何規范化等等這里不作為介…

Dart編程語言入門

Dart基礎入門語法介紹,詳細說明可以查看相關視頻《Dart編程語言入門》。 變量與常量 變量 1.使用 var 聲明變量,默認值為 null var a;//null a 10;2.顯示類型聲明 int a;//null a 10;3.使用 var 聲明,可賦予不同類型的值 var a; //null a 10; //int a…

《PHP精粹:編寫高效PHP代碼》——1.1節為什么要使用面向對象編程

本節書摘來自華章社區《PHP精粹:編寫高效PHP代碼》一書中的第1章,第1.1節為什么要使用面向對象編程,作者:(美)  Davey Shafik,更多章節內容可以訪問云棲社區“華章社區”公眾號查看 1.1 為什…

c語言數據結構系統化,C語言數據結構+數據庫+操作系統

http://cv.qiaobutang.com/post/55c419b20cf2009bd4607795第二部分是專業相關的C ,數據庫,操作系統,數據結構。http://c.biancheng.net/cpp/u/shuju/數據(Data)是信息的載體,它能夠被計算機識別、存儲和加工處理。它是計算機程序加…

c語言判斷一個序列是不是另一個的子序列

1 #include <stdio.h>2 #include <string.h>//添加字符串頭文件3 4 int Subsequence(char s[], char t[]) 5 {6 int m,n,i,j;7 n strlen(s); //n表示序列S的長度8 m strlen(t); //m表示序列T的長度9 i0; 10 j0; 11 if (m>…

linux中python如何調用matlab的數據_特征錦囊:如何在Python中處理不平衡數據

今日錦囊特征錦囊&#xff1a;如何在Python中處理不平衡數據? Index1、到底什么是不平衡數據2、處理不平衡數據的理論方法3、Python里有什么包可以處理不平衡樣本4、Python中具體如何處理失衡樣本印象中很久之前有位朋友說要我寫一篇如何處理不平衡數據的文章&#xff0c;整理…

源碼安裝zabbix遇到的報錯集錦

報錯1&#xff1a;checking for mysql_config... configure: error: MySQL library not found 解決辦法&#xff1a;查找mysql_config #find / -name "mysql_config*" /usr/local/mysql/bin/mysql_config 在配置時將原有的 --with-mysql 改為 --with-mysql/usr/loca…

pso算法c++語言代碼,一C++PSO(PSO)算法

收集和變化PSO算法&#xff0c;它可用于參考實施&#xff1a;#include #include #include #include #include #define rand_01 ((float)rand() / (float)RAND_MAX)const int numofdims 30;const int numofparticles 50;using namespace std;//typedef void (*FitnessFunc)(fl…

Hadoop不適合哪些場景 哪些場景適合?

Hadoop設計的目的主要包括下面幾個方面&#xff0c;也就是所謂的適用場景&#xff1a; 1&#xff1a;超大文件 可以是幾百M&#xff0c;幾百T這個級別的文件。 2&#xff1a;流式數據訪問 Hadoop適用于一次寫入&#xff0c;多次讀取的場景&#xff0c;也就是數據復制進去之后&a…

微服務 邊界服務_遵循這些實用原則以獲取精心設計的微服務邊界

微服務 邊界服務by Jake Lumetta杰克盧米塔(Jake Lumetta) 遵循這些實用原則以獲取精心設計的微服務邊界 (Follow these practical principles to get well-designed microservices boundaries) 如何避免使微服務太小和緊密耦合 (How to avoid making your microservices too …

ShareEntryActivity java.lang.ClassNotFoundException | Android類找不到問題

錯誤堆棧&#xff1a; Process: com.mci.smagazine, PID: 23265java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mci.smagazine/com.mci.smagazine.apshare.ShareEntryActivity}: java.lang.ClassNotFoundException: com.mci.smagazine.apshare…

阿里Android p6準備,項目經歷準備篇——如何準備阿里巴巴P6/P7前端面試

項目經歷準備篇——如何準備阿里巴巴P6/P7前端面試在上次的校招文章之后&#xff0c;有很多同學問有沒有社招相關的東西可以寫一篇&#xff0c;現在它來了。比起校招&#xff0c;社招更加看重項目經歷項目經歷反應的思考。本文針對的是想進入阿里的P6/P7同學&#xff0c;著重講…

for in for of區別_Python 第4課:for…in循環黃金搭檔之range()函數

樂學趣學Py● 04&#xff1a;for…in循環黃金搭檔之range()函數●Python趣味小百科Python中的繪圖模塊為什么叫Turtle海龜&#xff0c;而不是cat ,dog,bird呢&#xff1f;原來Python引用了麻省理工大學教授開發的logo海龜制圖語言,能通過繪圖直觀地教大家學習編程。實踐是最好的…

《游戲設計師修煉之道:數據驅動的游戲設計》一3.8小結

3.8小結 在玩游戲期間使用的數學知識通常相當簡單&#xff0c;盡管代碼中使用的數學知識可能非常復雜。玩家不希望由于在玩游戲期間不得不處理許多數字而分心&#xff0c;因為他們的大腦必須從控制角色的動作轉換到記住數字的含義。許多游戲回避了數字&#xff0c;而是通過像計…

ubuntu下安裝配置nfs

sudo apt-get install nfs-kernel-server sudo /nfs_root vim /etc/exports 在這個文件末尾添加 /nfs_root *(rw,sync,no_root_squash) 保存退出 重啟nfs服務 sudo /etc/init.d/rpcbind restart sudo /etc/init.d/nfs-kernel-server restart 測試 sudo mount 192.168.2.1:/nf…

使命愿景價值觀_為什么在制作產品時應該專注于愿景,價值,風險和先例

使命愿景價值觀by Steve史蒂夫(Steve) 為什么在制作產品時應該專注于愿景&#xff0c;價值&#xff0c;風險和先例 (Why you should focus on vision, value, risk, and precedent when making your product) 幾周前&#xff0c;產品開發人員John Cutler發表了一篇出色的文章&…

安卓前端布局Android,Android開發的幾種常見布局

目前正在從事iOS開發&#xff0c;對于安卓就是大學的時候自學了點&#xff0c;做過幾個小的項目&#xff0c;軟件外包大賽、計算機設計大賽、移動應用大賽都拿過獎項&#xff0c;呵呵。。。現在回想起來以前大學做的安卓比賽是多么的幼稚。 從現在開始我要從頭一步一步回顧安卓…

《Cocos2D權威指南》——3.9 本章小結

3.9 本章小結 本章對Cocos2D中的幾個核心類&#xff08;CCNode、CCScene、CCLayer、CCSprite&#xff09;進行了詳細介紹&#xff0c;并且通過節點層級圖讓大家了解到Cocos2D游戲的基本組成&#xff1b;然后介紹了Cocos2D中的單例。通過完善第2章的游戲實例&#xff0c;大家對…

永恒python圖片_python 數據詞云展示實例(3)- 背景圖設置

記錄wordcloud庫背景圖的設置及樣板 之前介紹了wordcloud的基本使用wordcloud的基本使用&#xff0c;本文記錄一下如何設置背景圖。 樣圖 背景圖tim.jpg 生成樣圖dream.png 樣板 from PIL import Image,ImageSequence image Image.open(tim.jpg)#打開背景圖 graph np.array(im…

創造的快樂

早上9點半到的圖書館&#xff0c;十點左右才進入狀態&#xff0c;上午和下午的一半時間都用來看AMD的GCN架構&#xff0c;看這種官方的文檔&#xff0c;和論文一樣&#xff0c;只看摘要和圖片&#xff0c;沒有死磕的精神&#xff0c;很難有收獲&#xff0c;結果就是&#xff0c…