使用fetch封装请求_关于如何使用Fetch API执行HTTP请求的实用ES6指南
使用fetch封裝請(qǐng)求
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 +)來(lái)執(zhí)行對(duì)REST API的 HTTP請(qǐng)求,并提供一些您很可能會(huì)遇到的實(shí)際示例。
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示例? 轉(zhuǎn)到第5節(jié)。第一部分描述使用HTTP請(qǐng)求時(shí)JavaScript的異步部分。
Note: All examples are written in ES6 with arrow functions.
注意 :所有示例均使用帶有箭頭功能的 ES6編寫(xiě)。
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.
在當(dāng)今的網(wǎng)絡(luò)/移動(dòng)應(yīng)用程序中,一種常見(jiàn)的模式是從服務(wù)器請(qǐng)求或顯示某種數(shù)據(jù)(例如用戶(hù),帖子,評(píng)論,訂閱,付款等),然后通過(guò)使用CRUD(創(chuàng)建,讀取,更新或刪除)操作。
To further manipulate a resource, we often use these JS methods (recommended) such as .map(), .filter() and .reduce().
為了進(jìn)一步處理資源,我們經(jīng)常使用這些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.如果您想成為一個(gè)更好的Web開(kāi)發(fā)人員,開(kāi)始自己的事業(yè),教別人,或者提高您的開(kāi)發(fā)技能,我將每周發(fā)布有關(guān)最新Web開(kāi)發(fā)語(yǔ)言的提示和技巧。這是我們要解決的問(wèn)題 (Here’s what we’ll address)
1.處理JS的異步HTTP請(qǐng)求 (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)的工作方式最具挑戰(zhàn)性的部分之一是了解如何處理異步請(qǐng)求,這要求并了解Promise和回調(diào)的工作方式。
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.
在大多數(shù)編程語(yǔ)言中,我們總是認(rèn)為操作是按順序發(fā)生的。 必須先執(zhí)行第一行,然后才能繼續(xù)進(jìn)行下一行。 這是有道理的,因?yàn)檫@是我們?nèi)祟?lèi)操作和完成日常任務(wù)的方式。
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,我們有多個(gè)在后臺(tái)/前景中運(yùn)行的操作,并且我們無(wú)法讓W(xué)eb應(yīng)用程序在每次等待用戶(hù)事件時(shí)都凍結(jié)。
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描述為異步可能會(huì)引起誤解。 準(zhǔn)確地說(shuō),JavaScript是同步的且具有各種回調(diào)機(jī)制的單線程。 。
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.
但是,有時(shí)必須按順序進(jìn)行操作,否則會(huì)導(dǎo)致混亂和意外結(jié)果。 因此,我們可以使用promise和回調(diào)來(lái)構(gòu)造它。 一個(gè)示例可能是在繼續(xù)下一個(gè)操作之前驗(yàn)證用戶(hù)憑據(jù)。
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,它允許在應(yīng)用運(yùn)行時(shí)通過(guò)與Web服務(wù)器交換數(shù)據(jù)來(lái)異步更新網(wǎng)頁(yè)。 簡(jiǎn)而言之,它實(shí)質(zhì)上意味著您可以更新網(wǎng)頁(yè)的某些部分而無(wú)需重新加載整個(gè)頁(yè)面(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是一個(gè)令人誤解的名稱(chēng)。 AJAX應(yīng)用程序可能使用XML來(lái)傳輸數(shù)據(jù),但是以純文本或JSON文本的形式傳輸數(shù)據(jù)同樣普遍。
一路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.
我已經(jīng)看到許多開(kāi)發(fā)人員對(duì)于將所有內(nèi)容都放在一個(gè)頁(yè)面應(yīng)用程序(SPA)中往往會(huì)感到非常興奮,這會(huì)導(dǎo)致很多異步痛苦! 但幸運(yùn)的是,我們擁有諸如Angular,VueJS和React之類(lèi)的庫(kù),使該過(guò)程變得更加簡(jiǎn)單實(shí)用。
Overall, it’s important to have a balance between what should reload the whole page or parts of the page.
總體而言,在重新加載整個(gè)頁(yè)面或頁(yè)面的一部分之間保持平衡非常重要。
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.
在大多數(shù)情況下,就功能強(qiáng)大的瀏覽器而言,頁(yè)面重新加載效果很好。 過(guò)去,頁(yè)面重新加載將花費(fèi)幾秒鐘(取決于服務(wù)器的位置和瀏覽器功能)。 但是今天的瀏覽器速度非常快,因此決定執(zhí)行AJAX還是頁(yè)面重新加載沒(méi)有太大的區(qū)別。
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.
我的個(gè)人經(jīng)驗(yàn)是,使用簡(jiǎn)單的搜索按鈕創(chuàng)建搜索引擎要比不使用按鈕創(chuàng)建搜索引擎容易和快捷得多。 而且在大多數(shù)情況下,客戶(hù)并不關(guān)心它是SPA還是額外的頁(yè)面重裝。 當(dāng)然,不要誤會(huì)我的意思,我確實(shí)喜歡SPA,但是我們需要考慮幾個(gè)折衷方案,如果我們處理預(yù)算有限且資源不足的情況,那么快速解決方案可能是更好的方法。
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.
最后,這實(shí)際上取決于用例,但我個(gè)人認(rèn)為,與簡(jiǎn)單的頁(yè)面重新加載相比,SPA需要更多的開(kāi)發(fā)時(shí)間和一些麻煩。
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.
這使我們可以向服務(wù)器執(zhí)行聲明性的HTTP請(qǐng)求。 對(duì)于每個(gè)請(qǐng)求,它都會(huì)創(chuàng)建一個(gè)Promise ,以解決該問(wèn)題,以定義內(nèi)容類(lèi)型和訪問(wèn)數(shù)據(jù)。
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.
現(xiàn)在,Fetch API的好處是JS生態(tài)系統(tǒng)完全支持它,并且它也是MDN Mozilla文檔的一部分。 最后但并非最不重要的一點(diǎn)是,它可以在大多數(shù)瀏覽器(IE除外)中使用。 從長(zhǎng)遠(yuǎn)來(lái)看,我猜想它將成為調(diào)用Web API的標(biāo)準(zhǔn)方法。
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一起使用,以及它如何在訂閱/取消訂閱等方面著重于內(nèi)存管理/泄漏。 也許知道,這將成為執(zhí)行HTTP請(qǐng)求的新標(biāo)準(zhǔn)方式。
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一起使用,以及它如何在訂閱/取消訂閱等方面著重于內(nèi)存管理/泄漏。 也許知道,這將成為執(zhí)行HTTP請(qǐng)求的新標(biāo)準(zhǔn)方式。
4.快速獲取API簡(jiǎn)介 (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()方法返回一個(gè)Promise ,該P(yáng)romise解析來(lái)自Request的Response以顯示狀態(tài)(成功與否)。 如果您在控制臺(tái)日志屏幕上收到此消息promise {} ,請(qǐng)不要驚慌-這基本上意味著Promise可以運(yùn)行,但正在等待解決。 因此,為了解決該問(wèn)題,我們需要.then()處理函數(shù)(回調(diào))來(lái)訪問(wèn)內(nèi)容。
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).
簡(jiǎn)而言之,我們首先定義路徑( Fetch ),其次從服務(wù)器請(qǐng)求數(shù)據(jù)( Request ),再定義內(nèi)容類(lèi)型( Body ),最后但并非最不重要的是,我們?cè)L問(wèn)數(shù)據(jù)( Response )。
If you struggle to understand this concept, don’t worry. You’ll get a better overview through the examples shown below.
如果您難以理解這個(gè)概念,請(qǐng)不要擔(dān)心。 通過(guò)下面顯示的示例,您將獲得更好的概述。
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.
如果要訪問(wèn)數(shù)據(jù),則需要兩個(gè).then()處理.then() (回調(diào))。 但是,如果要操縱資源,則只需要一個(gè).then()處理函數(shù)。 但是,我們可以使用第二個(gè)來(lái)確保已發(fā)送該值。
Basic Fetch API template:
基本提取API模板:
Note! The example above is just for illustrative purposes. The code will not work if you execute it.注意! 上面的示例僅用于說(shuō)明目的。 如果執(zhí)行該代碼,它將無(wú)法正常工作。提取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.
注意! 資源不會(huì)在服務(wù)器上真正創(chuàng)建,但是會(huì)返回假結(jié)果來(lái)模仿真實(shí)服務(wù)器。
1.顯示用戶(hù) (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.
如前所述,顯示單個(gè)用戶(hù)的過(guò)程由兩個(gè).then()處理程序(回調(diào))組成,第一個(gè)用于定義對(duì)象,第二個(gè)用于訪問(wèn)數(shù)據(jù)。
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.
注意,只需閱讀查詢(xún)字符串/users/2我們就能了解/預(yù)測(cè)API的功能。 有關(guān)如何編寫(xiě)高質(zhì)量REST API的更多信息,請(qǐng)查看Mahesh Haldar撰寫(xiě)的這些準(zhǔn)則提示。
例 (Example)
2.顯示用戶(hù)列表 (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.
該示例與上一個(gè)示例幾乎相同,除了查詢(xún)字符串是/users ,而不是/users/2 。
例 (Example)
3.創(chuàng)建一個(gè)新用戶(hù) (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.
這個(gè)看起來(lái)與前面的示例有些不同。 如果您不熟悉HTTP協(xié)議,那么它只是為我們提供了一些不錯(cuò)的方法,例如POST , GET , DELETE , UPDATE , PATCH和PUT 。 這些方法是動(dòng)詞,僅描述要執(zhí)行的操作的類(lèi)型,并且主要用于操縱服務(wù)器上的資源/數(shù)據(jù)。
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.
無(wú)論如何,為了使用Fetch API創(chuàng)建新用戶(hù),我們需要使用HTTP動(dòng)詞POST 。 但是首先,我們需要在某個(gè)地方定義它。 幸運(yùn)的是,有一個(gè)可選的參數(shù)Init我們可以將其與URL一起傳遞,以定義自定義設(shè)置,例如方法類(lèi)型,主體,憑據(jù),標(biāo)頭等。
Note: The fetch() method's parameters are identical to those of the Request() constructor.
注意: fetch()方法的參數(shù)與Request()構(gòu)造函數(shù)的參數(shù)相同。
例 (Example)
4.刪除用戶(hù) (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.
為了刪除用戶(hù),我們首先需要使用/users/1來(lái)定位用戶(hù),然后定義方法類(lèi)型為DELETE 。
例 (Example)
5.更新用戶(hù) (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動(dòng)詞PUT用于操作目標(biāo)資源,如果要進(jìn)行部分更改,則需要使用PATCH 。 有關(guān)這些HTTP動(dòng)詞的詳細(xì)信息, 請(qǐng)參閱。
例 (Example)
結(jié)論 (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.
現(xiàn)在,您已經(jīng)基本了解了如何使用JavaScript的Fetch API從服務(wù)器檢索或操縱資源,以及如何處理承諾。 您可以將本文用作如何構(gòu)造CRUD操作的API請(qǐng)求的指南。
Personally, I feel that the Fetch API is declarative and you can easily understand what is happening without any technical coding experience.
我個(gè)人認(rèn)為Fetch API是聲明性的,無(wú)需任何技術(shù)編碼經(jīng)驗(yàn),您就可以輕松了解正在發(fā)生的事情。
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請(qǐng)求中,在該請(qǐng)求中.then我們使用.then回調(diào)將請(qǐng)求鏈接。 這是許多開(kāi)發(fā)人員熟悉的標(biāo)準(zhǔn)方法,但是,如果要使用async/await請(qǐng)async/await 本文 。 除了async/await更易于讀寫(xiě)外,概念是相同的。
Here are a few articles I’ve written about the web-ecosystem along with personal programming tips and tricks.
這是我寫(xiě)的有關(guān)Web生態(tài)系統(tǒng)的幾篇文章,以及個(gè)人編程技巧和竅門(mén)。
A comparison between Angular and React
Angular和React之間的比較
A chaotic mind leads to chaotic code
混亂的頭腦導(dǎo)致混亂的代碼
Developers that constantly want to learn new things
不斷想學(xué)習(xí)新事物的開(kāi)發(fā)人員
A practical guide to ES6 modules
ES6模塊實(shí)用指南
Learn these core Web Concepts
了解這些核心Web概念
Boost your skills with these important JavaScript methods
這些重要JavaScript方法可提高您的技能
Program faster by creating custom bash commands
通過(guò)創(chuàng)建自定義bash命令來(lái)更快地編程
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.
您可以在我每周發(fā)布的“媒介”中找到我。 或者,您也可以在Twitter上關(guān)注我,我在其中發(fā)布了相關(guān)的Web開(kāi)發(fā)技巧和竅門(mén)以及個(gè)人故事。
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:如果您喜歡這篇文章并且想要更多類(lèi)似的文章,請(qǐng)拍手?并與可能需要它的朋友分享,這是很好的業(yè)障。
翻譯自: https://www.freecodecamp.org/news/a-practical-es6-guide-on-how-to-perform-http-requests-using-the-fetch-api-594c3d91a547/
使用fetch封裝請(qǐng)求
總結(jié)
以上是生活随笔為你收集整理的使用fetch封装请求_关于如何使用Fetch API执行HTTP请求的实用ES6指南的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 做梦梦到被朋友杀了是什么征兆
- 下一篇: 开源项目贡献者_我如何从一名贡献者转变为