您当前的位置:首页 > 互联网教程

JS中fetch()用法实例详解

发布时间:2025-05-22 10:57:33    发布人:远客网络

JS中fetch()用法实例详解

一、JS中fetch()用法实例详解

Fetch API提供了一个获取资源的接口,用于取代传统的 XMLHttpRequest,在JavaScript脚本中发出HTTP请求。它返回的是Promise对象,是为了取代传统xhr的不合理的写法而生的。相较于XMLHttpRequest,Fetch API的设计更为合理,采用模块化设计,API分散在多个对象上,更易于管理和维护。

Fetch API可以处理跨域请求,并且可以处理数据流,有利于提高网站性能表现,减少内存占用。相较于XMLHttpRequest,Fetch API采用数据流处理数据,可以分块读取,支持异步操作,可以将返回的JSON字符串反序列化为对象,被包装成一个Promise。

Fetch API的使用方式如下:fetch(url).then(...).catch(...)。示例:fetch('网址').then(response= response.json()).then(json= console.log(json))//获取到的json数据.catch(err= console.log('Request Failed', err))。

Fetch API请求成功后,得到的是一个Response对象。它包含的数据通过Stream接口异步读取,但还包含一些同步属性,例如HTTP回应的标头信息,可以立即读取。Response对象还有一Response.headers属性,指向一个Headers对象,可以使用forof循环进行遍历。

Response对象提供Response.clone()方法,可以创建Response对象的副本,实现多次读取。例如:const response1= await fetch('图片地址');const response2= response1.clone();const myBlob1= await response1.blob();const myBlob2= await response2.blob();

Fetch API的底层接口是Response.body,返回一个ReadableStream对象,供用户操作。可以用来分块读取内容,显示下载的进度。例如:const response= await fetch('图片地址');const reader= response.body.getReader();while(true){ const{done, value}= await reader.read();if(done){ break;} console.log(`Received${value.length} bytes`)}。

Fetch API的第二个参数可以作为配置对象,定制发出的HTTP请求。例如:fetch(url,{ method:"GET", headers:{"Content-Type":"text/plain;charset=UTF-8"}, body: undefined, mode:"cors", credentials:"same-origin", cache:"default", redirect:"follow", integrity:"", keepalive: false, signal: undefined});

Fetch API可以取消请求,使用AbortController对象。例如:let controller= new AbortController();fetch(url,{ signal: controller.signal});controller.abort()方法用于发出取消信号。可以监听controller.signal的值改变,触发abort事件。

二、【JavaScript】fetch

1、ajax:基于原生JavaScript的异步请求技术,使用XMLHttpRequest对象发送请求。

2、axios:基于Promise的HTTP客户端,适用于浏览器和Node.js,提供更高级别的封装。

3、fetch:浏览器内置API,现代化、基于Promise进行网络通信,功能及封装级别相对简单。

4、核心语法:使用全局fetch函数发起资源请求,返回一个Promise,响应后resolve传回Response对象。

5、发送get请求:结合URLSearchParams使用fetch进行,可使用.then的Promise写法。

6、发送get请求:结合URLSearchParams使用fetch。

7、核心步骤:发起fetch请求,处理返回的Promise。

8、发送JSON数据:使用fetch和Content-Type:application/json,发送JSON格式的数据。

9、核心步骤:创建fetch请求,设置Content-Type为application/json,使用JSON格式提交数据。

10、发送FormData:使用fetch,无需处理Content-Type,适用于表单数据提交。

11、核心步骤:创建fetch请求,使用FormData对象作为数据,无需设置Content-Type。

三、fetch跨域问题的使用详解

1、fetch提供了一个获取资源的接口,包括跨域资源。fetch的核心功能包括 Request, Response, Header, Body等,利用了请求的异步特性,它基于 promise。fetch是原生 JS提供的 API,专门用来取代 XHR对象。使用 fetch发起 Ajax请求,如 fetch('/url').then(data=> return data.text()).then(ret=> console.log(ret));

2、fetch的使用主要分为两步,首先获取到的是中间数据流对象,即 response类型对象。然后通过.then中获取到的数据才是真正的数据。例如:fetch("请求的url地址").then(response=> res.json()).then(data=> console.log(data))。第一个.then中获取到的不是最终数据,而是中间的数据流对象。

3、发起 Get请求时,fetch默认发起的是 Get请求,如 fetch("url").then(response=>{this response就是服务器返回的可读数据流,内部存储的是二进制数据。.json()的作用,就是读取 response这个二进制数据流,并把读取到的数据转为 JSON格式的 promise对象 return response.json()}).then(data=>{这离第二个.then中拿到的 data,就是最终的数据 console.log(data)})。

4、发起 Post请求时,需要先构建一个 URLSearchParams对象,然后调用 fetch方法,如 var sendDate= new URLSearchParams(); sendDate.append("name",'ls'); sendDate.append("age", 30); fetch("url",{ method:"post", body: sendDate//要发给服务器的数据}).then(response=> response.json()).then(data=> console.log(data))。另一种写法是:fetch(URL,{method:'post', body: JSON.stringify(obj), headers:{'Content-Type':'application/json'}}).then(function(response){return response.text();}).then(function(myJson){alert(myJson);});