使用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开发语言的提示和技巧。
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和回调来构造它。 一个示例可能是在继续下一个操作之前验证用户凭据。
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文本的形式传输数据同样普遍。
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需要更多的开发时间和一些麻烦。
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请求的新标准方式。
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 JSON
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.
注意! 上面的示例仅用于说明目的。 如果执行该代码,它将无法正常工作。
Note! The resource will not be really created on the server, but will return a fake result to mimic a real server.
注意! 资源不会在服务器上真正创建,但是会返回假结果来模仿真实服务器。
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撰写的这些准则提示。
The example is almost identical to the previous example except that the query string is /users
, and not /users/2
.
该示例与上一个示例几乎相同,除了查询字符串是/users
,而不是/users/2
。
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 theRequest()
constructor.注意:
fetch()
方法的参数与Request()
构造函数的参数相同。
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
。
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动词的详细信息, 请参阅。
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 useasync/await
check this article out. The concept is the same, exceptasync/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封装请求