使用fetch封装ajax_如何使用Fetch在JavaScript中进行AJAX调用

使用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, PATCH

    method :例如GET,POST,PATCH

  • headers: Headers object

    headersheaders头对象

  • mode: such as cors, no-cors, same-origin

    mode :例如corsno-corssame-origin

  • cache: cache mode for request

    cache :请求的缓存模式

  • 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

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

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

相关文章

RxJS笔记

RxJS 《深入浅出RxJS》读书笔记遗留问题 Observable的HOT与COLD对应的实际场景,以及在编码中的体现chapter1 html部分 测试你对时间的感觉按住我一秒钟然后松手你的时间:毫秒jquery实现 var time new Date().getTime(); $("#hold-me").moused…

滚动一定的高度底色递增

$(window).scroll(function() {var swipeHeight 200;//完全变色高度var scrollTop $(document).scrollTop();//页面滚动高度var x scrollTop/swipeHeight;$(".head-bg").css({"opacity":x}); }) 转载于:https://www.cnblogs.com/lhj-blog/p/8521525.htm…

@hot热加载修饰器导致static静态属性丢失(已解决)

react开发的时候,引入热加载,用了修饰器的引入方式,发现了一个很有意思的问题,网上并没有相关文章,所以抛出来探讨下。 一段很简单的测试代码。但是经过babel编码后,变得很有意思。假设编码成es2016&#x…

49. 字母异位词分组

49. 字母异位词分组 给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母都恰好只用一次。 示例 1: 输入: strs [“eat”, “tea”, “tan”…

python 入门程序_非Python程序员的Python速成课程-如何快速入门

python 入门程序This article is for people who already have experience in programming and want to learn Python quickly.本文适用于已经有编程经验并希望快速学习Python的人们。 I created this resource out of frustration when I couldnt find an online course or a…

cmd命令操作Oracle数据库

//注意cmd命令执行的密码字符不能过于复杂 不能带有特殊符号 以免执行不通过 譬如有!#¥%……&*之类的 所以在Oracle数据库设置密码是不要太复杂 /String Database "ORCL"; 不指向地址程序只能安装在数据库服务器上才能执行到命令String …

OpenCV学习(7.16)

写了个实现摄像头上画线并输出角度的东西……虽然很简单,但脑残的我还是debug了很长时间。 1 // 圆和直线.cpp : 定义控制台应用程序的入口点。2 //3 4 #include "stdafx.h"5 6 using namespace std;7 using namespace cv;8 9 void onMouse(int event, in…

学习vue.js的自我梳理笔记

基本语法格式&#xff1a; <script> new Vue({ el: #app, data: { url: http://www.runoob.com } }) </script> 指令 【指令是带有 v- 前缀的特殊属性。】 判断 <p v-if"seen">现在你看到我了</p> 参数 <a v-bind:href"url"&…

722. 删除注释

722. 删除注释 给一个 C 程序&#xff0c;删除程序中的注释。这个程序source是一个数组&#xff0c;其中source[i]表示第i行源码。 这表示每行源码由\n分隔。 在 C 中有两种注释风格&#xff0c;行内注释和块注释。 字符串// 表示行注释&#xff0c;表示//和其右侧的其余字符…

如何创建一个自记录的Makefile

My new favorite way to completely underuse a Makefile? Creating personalized, per-project repository workflow command aliases that you can check in.我最喜欢的完全没用Makefile的方法&#xff1f; 创建个性化的按项目存储库工作流命令别名&#xff0c;您可以检入。…

【BZOJ3262】陌上花开

CDQ分治模板 注意三元组完全相等的情况 1 #include<bits/stdc.h>2 using namespace std;3 const int N100010,K200010;4 int n,k,cnt[N],ans[N];5 struct Node{6 int a,b,c,id;7 bool operator<(const Node& k)const{8 if(bk.b&&ck.c) re…

Spring+jpaNo transactional EntityManager available

2019独角兽企业重金招聘Python工程师标准>>> TransactionRequiredException: No transactional EntityManager availableEntityManager执行以下方法(refresh, persist, flush, joinTransaction, remove, merge) 都需要需要事务if (transactionRequiringMethods.cont…

python项目构建_通过构建4个项目来学习Python网络

python项目构建The Python programming language is very capable when it comes to networking. Weve released a crash course on the freeCodeCamp.org YouTube channel that will help you learn the basics of networking in Python.当涉及到网络时&#xff0c;Python编程…

164. 最大间距

164. 最大间距 给定一个无序的数组&#xff0c;找出数组在排序之后&#xff0c;相邻元素之间最大的差值。 如果数组元素个数小于 2&#xff0c;则返回 0。 示例 1: 输入: [3,6,9,1] 输出: 3 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差…

10.32/10.33 rsync通过服务同步 10.34 linux系统日志 screen工具

通过后台服务的方式在远程主机上建立一个rsync的服务器&#xff0c;在服务器上配置好rsync的各种应用&#xff0c;然后将本机作为rsync的一个客户端连接远程的rsync服务器。在128主机上建立并配置rsync的配置文件/etc/rsyncd.conf,把你的rsyncd.conf编辑成以下内容&#xff1a;…

01_Struts2概述及环境搭建

1.Struts2概述&#xff1a;Struts2是一个用来开发MVC应用程序的框架。Struts2提供了web应用程序开发过程中一些常见问题的解决方案;对用户输入的数据进行合法性验证统一的布局可扩展性国际化和本地化支持Ajax表单的重复提交文件的上传和下载... ...2.Struts2相对于Struts1的优势…

315. 计算右侧小于当前元素的个数

315. 计算右侧小于当前元素的个数 给定一个整数数组 nums&#xff0c;按要求返回一个新数组 counts。数组 counts 有该性质&#xff1a; counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。 示例&#xff1a; 输入&#xff1a;nums [5,2,6,1] 输出&#xff1a;[2,1…

IOS上传文件给java服务器,返回报错unacceptable context-type:text/plain

IOS上传文件给java服务器&#xff0c;返回报错unacceptable context-type&#xff1a;text/plain response返回类型不对 RequestMapping(value "uploadMultiFiles", method RequestMethod.POST, produces"application/json;charsetUTF-8") 使用produces指…

Python爬虫框架Scrapy学习笔记原创

字号scrapy [TOC] 开始 scrapy安装 首先手动安装windows版本的Twisted https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted pip install Twisted-18.4.0-cp36-cp36m-win_amd64.whl 安装scrapy pip install -i https://pypi.douban.com/simple/ scrapy windows系统额外需要…

600. 不含连续1的非负整数

600. 不含连续1的非负整数 给定一个正整数 n&#xff0c;找出小于或等于 n 的非负整数中&#xff0c;其二进制表示不包含 连续的1 的个数。 示例 1:输入: 5 输出: 5 解释: 下面是带有相应二进制表示的非负整数< 5&#xff1a; 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101…