使用fetch封装请求_关于如何使用Fetch API执行HTTP请求的实用ES6指南
使用fetch封裝請求
In this guide, I’ll show you how to use the Fetch API (ES6+) to perform HTTP requests to an REST API with some practical examples you’ll most likely encounter.
在本指南中,我將向您展示如何使用Fetch API(ES6 +)來執行對REST API的 HTTP請求,并提供一些您很可能會遇到的實際示例。
Want to quickly see the HTTP examples? Go to section 5. The first part describes the asynchronous part of JavaScript when working with HTTP requests.
是否想快速查看HTTP示例? 轉到第5節。第一部分描述使用HTTP請求時JavaScript的異步部分。
Note: All examples are written in ES6 with arrow functions.
注意 :所有示例均使用帶有箭頭功能的 ES6編寫。
A common pattern in today’s current web/mobile applications is to request or show some sort of data from the server (such as users, posts, comments, subscriptions, payments and so forth) and then manipulate it by using CRUD (create, read, update or delete) operations.
在當今的網絡/移動應用程序中,一種常見的模式是從服務器請求或顯示某種數據(例如用戶,帖子,評論,訂閱,付款等),然后通過使用CRUD(創建,讀取,更新或刪除)操作。
To further manipulate a resource, we often use these JS methods (recommended) such as .map(), .filter() and .reduce().
為了進一步處理資源,我們經常使用這些JS方法 (推薦),例如.map() .filter()和.filter() .reduce() 。
If you want to become a better web developer, start your own business, teach others, or improve your development skills, I’ll be posting weekly tips and tricks on the latest web development languages.如果您想成為一個更好的Web開發人員,開始自己的事業,教別人,或者提高您的開發技能,我將每周發布有關最新Web開發語言的提示和技巧。這是我們要解決的問題 (Here’s what we’ll address)
1.處理JS的異步HTTP請求 (1. Dealing with JS’s asynchronous HTTP requests)
One of the most challenging parts with understanding how JavaScript (JS) works is understanding how to deal with asynchronous requests, which requires and understanding in how promises and callbacks work.
理解JavaScript(JS)的工作方式最具挑戰性的部分之一是了解如何處理異步請求,這要求并了解Promise和回調的工作方式。
In most programming languages, we are wired to think that operations happen in order (sequentially). The first line must be executed before we can move on to the next line. It make sense because that is how we humans operate and complete daily tasks.
在大多數編程語言中,我們總是認為操作是按順序發生的。 必須先執行第一行,然后才能繼續進行下一行。 這是有道理的,因為這是我們人類操作和完成日常任務的方式。
But with JS, we have multiple operations that are running in the background/foreground, and we cannot have a web app that freezes every time it waits for a user event.
但是,使用JS,我們有多個在后臺/前景中運行的操作,并且我們無法讓Web應用程序在每次等待用戶事件時都凍結。
Describing JavaScript as asynchronous is perhaps misleading. It’s more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms. Read more.
將JavaScript描述為異步可能會引起誤解。 準確地說,JavaScript是同步的且具有各種回調機制的單線程。 。
Nevertheless, sometimes things must happen in order, otherwise it will cause chaos and unexpected results. For that reason, we may use promises and callbacks to structure it. An example could be validating user credentials before proceeding to the next operation.
但是,有時必須按順序進行操作,否則會導致混亂和意外結果。 因此,我們可以使用promise和回調來構造它。 一個示例可能是在繼續下一個操作之前驗證用戶憑據。
2.什么是AJAX (2. What is AJAX)
AJAX stands for Asynchronous JavaScript and XML, and it allows web pages to be updated asynchronously by exchanging data with a web server while the app is running. In short, it essentially means that you can update parts of a web page without reloading the whole page (the URL stays the same).
AJAX代表異步JavaScript和XML,它允許在應用運行時通過與Web服務器交換數據來異步更新網頁。 簡而言之,它實質上意味著您可以更新網頁的某些部分而無需重新加載整個頁面(URL保持不變)。
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.
AJAX是一個令人誤解的名稱。 AJAX應用程序可能使用XML來傳輸數據,但是以純文本或JSON文本的形式傳輸數據同樣普遍。
一路AJAX? (AJAX all the way?)
I’ve seen that many developers tend to get really excited about having everything in a single page application (SPA), and this leads to lots of asynchronous pain! But luckily, we have libraries such as Angular, VueJS and React that makes this process a whole lot easier and practical.
我已經看到許多開發人員對于將所有內容都放在一個頁面應用程序(SPA)中往往會感到非常興奮,這會導致很多異步痛苦! 但幸運的是,我們擁有諸如Angular,VueJS和React之類的庫,使該過程變得更加簡單實用。
Overall, it’s important to have a balance between what should reload the whole page or parts of the page.
總體而言,在重新加載整個頁面或頁面的一部分之間保持平衡非常重要。
And in most cases, a page reload works fine in terms of how powerful browsers have become. Back in the days, a page reload would take seconds (depending on the location of the server and browser capabilities). But today’s browsers are extremely fast so deciding whether to perform AJAX or page reload is not that of a big difference.
在大多數情況下,就功能強大的瀏覽器而言,頁面重新加載效果很好。 過去,頁面重新加載將花費幾秒鐘(取決于服務器的位置和瀏覽器功能)。 但是今天的瀏覽器速度非常快,因此決定執行AJAX還是頁面重新加載沒有太大的區別。
My personal experience is that it’s a lot easier and faster to create a search engine with a simple search button than doing it without a button. And in most cases, the customer doesn’t care if it is a SPA or an extra page-reload. Of course, don’t get me wrong, I do love SPAs, but we need to consider a couple of trade-offs, if we deal with limited budget and lack of resources then maybe a quick solution is better approach.
我的個人經驗是,使用簡單的搜索按鈕創建搜索引擎要比不使用按鈕創建搜索引擎容易和快捷得多。 而且在大多數情況下,客戶并不關心它是SPA還是額外的頁面重裝。 當然,不要誤會我的意思,我確實喜歡SPA,但是我們需要考慮幾個折衷方案,如果我們處理預算有限且資源不足的情況,那么快速解決方案可能是更好的方法。
In the end, it really depends on the use case, but personally I feel that SPAs require more development time and a bit of headache than a simple page reload.
最后,這實際上取決于用例,但我個人認為,與簡單的頁面重新加載相比,SPA需要更多的開發時間和一些麻煩。
3.為什么要提取API? (3. Why Fetch API?)
This allows us to perform declarative HTTP requests to a server. For each request, it creates a Promise which must be resolved in order to define the content type and access the data.
這使我們可以向服務器執行聲明性的HTTP請求。 對于每個請求,它都會創建一個Promise ,以解決該問題,以定義內容類型和訪問數據。
Now the benefit of Fetch API is that it is fully supported by the JS ecosystem, and is also a part of the MDN Mozilla docs. And last but not least, it works out of the box on most browsers (except IE). In the long-term, I’m guessing it will become the standard way of calling web APIs.
現在,Fetch API的好處是JS生態系統完全支持它,并且它也是MDN Mozilla文檔的一部分。 最后但并非最不重要的一點是,它可以在大多數瀏覽器(IE除外)中使用。 從長遠來看,我猜想它將成為調用Web API的標準方法。
Note! I’m well aware other HTTP approaches such as using Observable with RXJS, and how it focuses on memory-management/leak in terms of subscribe/unsubscribe and so forth. And maybe that will become the new standard way of doing HTTP requests, who knows?
注意! 我很清楚其他HTTP方法,例如將Observable與RXJS一起使用,以及它如何在訂閱/取消訂閱等方面著重于內存管理/泄漏。 也許知道,這將成為執行HTTP請求的新標準方式。
Note! I’m well aware other HTTP approaches such as using Observable with RXJS, and how it focuses on memory-management/leak in terms of subscribe/unsubscribe and so forth. And maybe that will become the new standard way of doing HTTP requests, who knows?
注意! 我很清楚其他HTTP方法,例如將Observable與RXJS一起使用,以及它如何在訂閱/取消訂閱等方面著重于內存管理/泄漏。 也許知道,這將成為執行HTTP請求的新標準方式。
4.快速獲取API簡介 (4. A quick intro to Fetch API)
The fetch() method returns a Promise that resolves the Response from the Request to show the status (successful or not). If you ever get this message promise {} in your console log screen, don’t panic — it basically means that the Promise works, but is waiting to be resolved. So in order to resolve it we need the .then() handler (callback) to access the content.
fetch()方法返回一個Promise ,該Promise解析來自Request的Response以顯示狀態(成功與否)。 如果您在控制臺日志屏幕上收到此消息promise {} ,請不要驚慌-這基本上意味著Promise可以運行,但正在等待解決。 因此,為了解決該問題,我們需要.then()處理函數(回調)來訪問內容。
So in short, we first define the path (Fetch), secondly request data from the server (Request), thirdly define the content type (Body) and last but not least, we access the data (Response).
簡而言之,我們首先定義路徑( Fetch ),其次從服務器請求數據( Request ),再定義內容類型( Body ),最后但并非最不重要的是,我們訪問數據( Response )。
If you struggle to understand this concept, don’t worry. You’ll get a better overview through the examples shown below.
如果您難以理解這個概念,請不要擔心。 通過下面顯示的示例,您將獲得更好的概述。
The path we'll be using for our examples https://jsonplaceholder.typicode.com/users // returns JSON5.提取API-HTTP示例 (5. Fetch API - HTTP examples)
If we want to access the data, we need two .then() handlers (callback). But if we want to manipulate the resource, we need only one .then() handler. However, we can use the second one to make sure the value has been sent.
如果要訪問數據,則需要兩個.then()處理.then() (回調)。 但是,如果要操縱資源,則只需要一個.then()處理函數。 但是,我們可以使用第二個來確保已發送該值。
Basic Fetch API template:
基本提取API模板:
Note! The example above is just for illustrative purposes. The code will not work if you execute it.注意! 上面的示例僅用于說明目的。 如果執行該代碼,它將無法正常工作。提取API示例 (Fetch API examples)
Note! The resource will not be really created on the server, but will return a fake result to mimic a real server.
注意! 資源不會在服務器上真正創建,但是會返回假結果來模仿真實服務器。
1.顯示用戶 (1. Showing a user)
As previously mentioned, the process of showing a single user consists of two .then() handlers (callback), the first one to define the object, and the second one to access the data.
如前所述,顯示單個用戶的過程由兩個.then()處理程序(回調)組成,第一個用于定義對象,第二個用于訪問數據。
Notice just by reading the query string /users/2 we are able to understand/predict what the API does. For more information on how to write high-quality REST API, check out these guidelines tip written by Mahesh Haldar.
注意,只需閱讀查詢字符串/users/2我們就能了解/預測API的功能。 有關如何編寫高質量REST API的更多信息,請查看Mahesh Haldar撰寫的這些準則提示。
例 (Example)
2.顯示用戶列表 (2. Showing a list of users)
The example is almost identical to the previous example except that the query string is /users, and not /users/2.
該示例與上一個示例幾乎相同,除了查詢字符串是/users ,而不是/users/2 。
例 (Example)
3.創建一個新用戶 (3. Creating a new user)
This one looks a bit different from the previous example. If you are not familiar with the HTTP protocol, it simply provides us with a couple of sweet methods such as POST, GET,DELETE, UPDATE, PATCH and PUT. These methods are verbs that simply describe the type of action to be executed, and are mostly used to manipulate the resource/data on the server.
這個看起來與前面的示例有些不同。 如果您不熟悉HTTP協議,那么它只是為我們提供了一些不錯的方法,例如POST , GET , DELETE , UPDATE , PATCH和PUT 。 這些方法是動詞,僅描述要執行的操作的類型,并且主要用于操縱服務器上的資源/數據。
Anyway, in order to create a new user with Fetch API, we’ll need to use the HTTP verb POST. But first, we need to define it somewhere. Luckily, there is an optional argument Init we can pass along with the URL for defining custom settings such as method type, body, credentials, headers and so forth.
無論如何,為了使用Fetch API創建新用戶,我們需要使用HTTP動詞POST 。 但是首先,我們需要在某個地方定義它。 幸運的是,有一個可選的參數Init我們可以將其與URL一起傳遞,以定義自定義設置,例如方法類型,主體,憑據,標頭等。
Note: The fetch() method's parameters are identical to those of the Request() constructor.
注意: fetch()方法的參數與Request()構造函數的參數相同。
例 (Example)
4.刪除用戶 (4. Deleting a user)
In order to delete the user, we first need to target the user with /users/1, and then we define the method type which is DELETE.
為了刪除用戶,我們首先需要使用/users/1來定位用戶,然后定義方法類型為DELETE 。
例 (Example)
5.更新用戶 (5. Updating a user)
The HTTP verb PUT is used to manipulate the target resource, and if you want to do partial changes, you’ll need to use PATCH. For more information on what these HTTP verbs do, check this out.
HTTP動詞PUT用于操作目標資源,如果要進行部分更改,則需要使用PATCH 。 有關這些HTTP動詞的詳細信息, 請參閱。
例 (Example)
結論 (Conclusion)
Now you have a basic understanding of how to retrieve or manipulate a resource from the server using JavaScript’s Fetch API, as well as how to deal with promises. You can use this article as a guide for how to structure your API requests for CRUD operations.
現在,您已經基本了解了如何使用JavaScript的Fetch API從服務器檢索或操縱資源,以及如何處理承諾。 您可以將本文用作如何構造CRUD操作的API請求的指南。
Personally, I feel that the Fetch API is declarative and you can easily understand what is happening without any technical coding experience.
我個人認為Fetch API是聲明性的,無需任何技術編碼經驗,您就可以輕松了解正在發生的事情。
All examples are shown in promised-base request where we chain the request using .then callback. This is a standard approach which many devs are familiar with, however, if you want to use async/await check this article out. The concept is the same, except async/await is easier to read and write.
所有示例均顯示在promise-base請求中,在該請求中.then我們使用.then回調將請求鏈接。 這是許多開發人員熟悉的標準方法,但是,如果要使用async/await請async/await 本文 。 除了async/await更易于讀寫外,概念是相同的。
Here are a few articles I’ve written about the web-ecosystem along with personal programming tips and tricks.
這是我寫的有關Web生態系統的幾篇文章,以及個人編程技巧和竅門。
A comparison between Angular and React
Angular和React之間的比較
A chaotic mind leads to chaotic code
混亂的頭腦導致混亂的代碼
Developers that constantly want to learn new things
不斷想學習新事物的開發人員
A practical guide to ES6 modules
ES6模塊實用指南
Learn these core Web Concepts
了解這些核心Web概念
Boost your skills with these important JavaScript methods
這些重要JavaScript方法可提高您的技能
Program faster by creating custom bash commands
通過創建自定義bash命令來更快地編程
You can find me on Medium where I publish on a weekly basis. Or you can follow me on Twitter, where I post relevant web development tips and tricks along with personal stories.
您可以在我每周發布的“媒介”中找到我。 或者,您也可以在Twitter上關注我,我在其中發布了相關的Web開發技巧和竅門以及個人故事。
P.S. If you enjoyed this article and want more like these, please clap ? and share with friends that may need it, it’s good karma.
PS:如果您喜歡這篇文章并且想要更多類似的文章,請拍手?并與可能需要它的朋友分享,這是很好的業障。
翻譯自: https://www.freecodecamp.org/news/a-practical-es6-guide-on-how-to-perform-http-requests-using-the-fetch-api-594c3d91a547/
使用fetch封裝請求
總結
以上是生活随笔為你收集整理的使用fetch封装请求_关于如何使用Fetch API执行HTTP请求的实用ES6指南的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到被朋友杀了是什么征兆
- 下一篇: 梦到别人送我桃子好不好