使用fetch封裝ajax
I will be sharing bite sized learnings about JavaScript regularly in this series. We'll cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.
在本系列中,我將定期分享有關JavaScript的小知識。 我們將介紹JS基礎知識,瀏覽器,DOM,系統設計,域架構和框架。
Fetch is an interface for making an AJAX request in JavaScript. It is implemented widely by modern browsers and is used to call an API.
Fetch是用于在JavaScript中發出AJAX請求的接口。 它由現代瀏覽器廣泛實現,并用于調用API。
const promise = fetch(url, [options])
Calling fetch returns a promise, with a Response object. The promise is rejected if there is a network error, and it's resolved if there is no problem connecting to the server and the server responded a status code. This status code could be 200s, 400s or 500s.
調用fetch返回帶有響應對象的Promise。 如果出現網絡錯誤,則將拒絕諾言;如果連接到服務器沒有問題,并且服務器響應了狀態代碼,則可以解決諾言。 此狀態碼可以是200s,400s或500s。
A sample FETCH request -
樣本FETCH請求-
fetch(url).then(response => response.json()).catch(err => console.log(err))
The request is sent as a GET by default. To send a POST / PATCH / DELETE / PUT you can use the method property as part of options
parameter. Some other possible values options
can take -
默認情況下,該請求作為GET發送。 要發送POST / PATCH / DELETE / PUT,您可以將method屬性用作options
參數的一部分。 其他一些可能的值options
可以采用-
method
: such as GET, POST, PATCHmethod
:例如GET,POST,PATCHheaders
: Headers objectheaders
:headers
頭對象mode
: such ascors
,no-cors
,same-origin
mode
:例如cors
,no-cors
,same-origin
cache
: cache mode for requestcache
:請求的緩存模式credentials
credentials
body
body
Check out the full list of available options here
在此處查看可用選項的完整列表
Example usage: This example demonstrates the usage of fetch to call an API and to get a list of git repositories.
用法示例:此示例演示fetch的用法,以調用API并獲取git存儲庫列表。
const url = 'https://api.github.com/users/shrutikapoor08/repos';fetch(url).then(response => response.json()).then(repos => {const reposList = repos.map(repo => repo.name);console.log(reposList);})
.catch(err => console.log(err))
To send a POST request, here's how the method parameter can be used with async / await syntax.
要發送POST請求,以下是method參數與async / await語法一起使用的方式。
const params = {id: 123
}const response = await fetch('url', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(params)
});const data = await response.json();
對更多JSBytes感興趣? 訂閱新聞通訊 (Interested in more JSBytes? Sign up for the newsletter)
翻譯自: https://www.freecodecamp.org/news/how-to-use-fetch-api/
使用fetch封裝ajax