使用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. Dealing with JS’s asynchronous HTTP requests

    处理JS的异步HTTP请求
  2. What is AJAX?

    什么是AJAX?
  3. Why Fetch API?

    为什么要提取API?
  4. A quick intro to Fetch API

    Fetch API快速入门
  5. Fetch API - CRUD examples ← the good stuff!

    获取API-CRUD示例←好东西!

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解析来自RequestResponse以显示状态(成功与否)。 如果您在控制台日志屏幕上收到此消息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

5.提取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)

  1. Showing a user

    显示用户
  2. Showing a list of users

    显示用户列表
  3. Creating a new user

    创建一个新用户
  4. Deleting a user

    删除用户
  5. Updating a user

    更新用户

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协议,那么它只是为我们提供了一些不错的方法,例如POSTGETDELETEUPDATEPATCHPUT 。 这些方法是动词,仅描述要执行的操作的类型,并且主要用于操纵服务器上的资源/数据。

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/awaitasync/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封装请求

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393190.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

hadoop集群中客户端修改、删除文件失败

这是因为hadoop集群在启动时自动进入安全模式 查看安全模式状态:hadoop fs –safemode get 进入安全模式状态:hadoop fs –safemode enter 退出安全模式状态:hadoop fs –safemode leave转载于:https://www.cnblogs.com/lishengnan/p/a123.ht…

OpenStack nova-network 支持多vlan技术实现片段代码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

Rest API

什么是接口测试 接口测试又称 API 测试 Application Programming Interface 接口测试是测试系统组件间接口的一种测试。重点关注数据传递。 接口测试一般会用于多系统间交互开发,或者拥有多个子系统的应用系统开发的测试。 为什么要做接口测试 很多系统关联都是基于…

php循环checkbox,php循环删除checkbox | 学步园

一、首先要了解sql语句$SQLdelete from user where id in (1,2,4);表单大概是:form action methodpost input nameID_Dele[] typecheckbox idID_Dele[] value1input nameID_Dele[] typecheckbox idID_Dele[] value2input nameID_Dele[] type首先要了解sql语句$SQL&q…

leetcode1451. 重新排列句子中的单词(排序)

「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text : 句子的首字母大写 text 中的每个单词都用单个空格分隔。 请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序…

Java+Oracle实现事务——JDBC事务

J2EE支持JDBC事务、JTA事务和容器事务事务,这里说一下怎样实现JDBC事务。 JDBC事务是由Connection对象所控制的,它提供了两种事务模式:自己主动提交和手动提交,默认是自己主动提交。 自己主动提交就是:在JDBC中。在一个…

开源项目贡献者_我如何从一名贡献者转变为一个开源项目维护者

开源项目贡献者by Dhanraj Acharya通过Dhanraj Acharya 我如何从一名贡献者转变为一个开源项目维护者 (How I went from being a contributor to an Open Source project maintainer) I was a lone software developer. When I was in college, I attended the KDE conference…

网络摄像头CVE

CVE-2018-9995 rtsp未授权访问 rtsp后缀整理: Axis(安讯士) rtsp:// 192.168.200.202/axis-media/media.amp?videocodech264&resolution1280x720 rtsp://IP地址/mpeg4/media.amp rtsp://IP地址/安迅士/AXIS-media/media.amp123D-Link …

Centos中不从skel目录里向其中复制任何文件错误的解决方法

[rootlocalhost www]# useradd -d /webserver/www/ ithovcom useradd:警告:此主目录已经存在。 不从 skel 目录里向其中复制任何文件。 [rootlocalhost www]# ls -a .&http://www.aliyun.com/zixun/aggregation/37954.html">nbsp; .. 发现没…

leetcode91. 解码方法

一条包含字母 A-Z 的消息通过以下方式进行了编码: ‘A’ -> 1 ‘B’ -> 2 … ‘Z’ -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。 示例 1: 输入: “12” 输出: 2 解释: 它可以解码为 “AB”(1 2)或者…

php 系统平均负载,Linux_解析Linux系统的平均负载概念,一、什么是系统平均负载(Load a - phpStudy...

解析Linux系统的平均负载概念一、什么是系统平均负载(Load average)?在Linux系统中,uptime、w、top等命令都会有系统平均负载load average的输出,那么什么是系统平均负载呢?系统平均负载被定义为在特定时间间隔内运行队列中的平均…

Elastic-job使用及原理

一、原理 elastic-job有lite版和cloud版,最大的区别是有无调度中心,笔者采用的是lite版本,无中心化。 tips: 第一台服务器上线触发主服务器选举。主服务器一旦下线,则重新触发选举,选举过程中阻塞,只有主服…

构建持续交付_如何使交付成为您的重点将如何帮助您构建高质量的应用程序

构建持续交付by Simon Schwartz西蒙施瓦茨(Simon Schwartz) 如何使交付成为您的重点将如何帮助您构建高质量的应用程序 (How making delivery your focus will help you build quality applications) I was recently asked by our company’s executive team why our team was…

微信退款通知,退款回调数据解密.SHA256签名AEAD_AES_256_GCM解密

$xmlResult file_get_contents("php://input");//获取微信的数据$result $this->xmlToArray($xmlResult);//将xml转成数组 // 将加密的数据解密,方法在下面$reqInfo $this->refund_decrypt($result[req_info]); /** 退款通知解密* Author WangZhaoBo* param…

BeanShell自动装箱拆箱

“装箱”和“拆箱”是用来描述自动包装一个原始类型到一个包装类以及在必要时解开包装回到原始类型的术语。装箱是 Java 的特性(SDK 1.5)之一,且 BeanShell 已支持多年。 BeanShell 支持原始类型的装箱和拆箱。比如: int i5; Inte…

leetcode816. 模糊坐标

我们有一些二维坐标,如 “(1, 3)” 或 “(2, 0.5)”,然后我们移除所有逗号,小数点和空格,得到一个字符串S。返回所有可能的原始字符串到一个列表中。 原始的坐标表示法不会存在多余的零,所以不会出现类似于"00&q…

IO流入门-第十二章-ObjectInputStream_ObjectOutputStream

DataInputStream和DataOutputStream基本用法和方法示例,序列化和反序列化 import java.io.Serializable; //该接口是一个“可序列化”的 ,没有任何方法,是一个标识接口,还有Cloneable /*标识接口的作用:标识作用…

matlab pca重构,Matlab – PCA分析和重建多维数据

这是一个快速的演练.首先我们创建一个隐藏变量的矩阵.它有100个观察,有两个特点.>> Y randn(100,2);现在创建一个加载矩阵.这将把隐藏的变量映射到观察到的变量上.说你观察到的变量有四个特征.那么你的加载矩阵需要是24>> W [1 1; 1 -1; 2 1; 2 -1];这告诉你,观察…

文档对象模型dom_什么是文档对象模型,以及为什么应该知道如何使用它。

文档对象模型domby Leonardo Maldonado莱昂纳多马尔多纳多(Leonardo Maldonado) 什么是文档对象模型,以及为什么应该知道如何使用它。 (What’s the Document Object Model, and why you should know how to use it.) So, you’ve studied HTML, you’ve created y…

安装Docker step by step

1. 系统要求 centos7以上 使用cat /etc/redhat-release查看系统版本,我的Centos 7.6 centos-extra 仓库 enable,默认是打开的 2.安装docker docer安装分为联网安装和离线安装两种安装 方式, 第一种 在有外网环境下安装docker,一般使用yum安…