fetch API

一.什么是fetch?

  fetch的作用类似于XMLHttpRequet的作用,用于异步请求网络,其提供的API更加的完善.

  fetch提供了Request和Response对象的定义,用于自定义网络请求和处理响应消息,兼容性

  还不是很强.

二.如何使用fetch?

  fetch提供一系列的API,如下:

  GlobalFetch:

    包括fetch()方法用于获取资源

  Headers:

    表示response/request的消息头

  Request:

    用于请求资源

  Response:

    一个request的响应消息

  Body

    消息的内容

三.开始使用fetch

  1.检查兼容性

    

1 if(self.fetch) {
2     // run my fetch request here
3 } else {
4     // do something with XMLHttpRequest?
5 }

  2.发送一个请求

  

 1 var myImage = document.querySelector(‘img‘);
 2
 3 fetch(‘flowers.jpg‘)
 4 .then(function(response) {
 5   return response.blob();
 6 })
 7 .then(function(myBlob) {
 8   var objectURL = URL.createObjectURL(myBlob);
 9   myImage.src = objectURL;
10 });

  这里是获取图片,并插入到相应位置

  3.用于配置请求的一些的选项

  

 1 var myHeaders = new Headers();
 2
 3 var myInit = { method: ‘GET‘,
 4                headers: myHeaders,
 5                mode: ‘cors‘,
 6                cache: ‘default‘ };
 7
 8 fetch(‘flowers.jpg‘,myInit)
 9 .then(function(response) {
10   return response.blob();
11 })
12 .then(function(myBlob) {
13   var objectURL = URL.createObjectURL(myBlob);
14   myImage.src = objectURL;
15 });

  4.检查请求是否成功

  

 1 fetch(‘flowers.jpg‘).then(function(response) {
 2   if(response.ok) {
 3     response.blob().then(function(myBlob) {
 4       var objectURL = URL.createObjectURL(myBlob);
 5       myImage.src = objectURL;
 6     });
 7   } else {
 8     console.log(‘Network response was not ok.‘);
 9   }
10 })
11 .catch(function(error) {
12   console.log(‘There has been a problem with your fetch operation: ‘ + error.message);
13 });

  5.可以自定义一个Request对象

  

 1 var myHeaders = new Headers();
 2
 3 var myInit = { method: ‘GET‘,
 4                headers: myHeaders,
 5                mode: ‘cors‘,
 6                cache: ‘default‘ };
 7
 8 var myRequest = new Request(‘flowers.jpg‘,myInit);
 9
10 fetch(myRequest,myInit)
11 .then(function(response) {
12   return response.blob();
13 })
14 .then(function(myBlob) {
15   var objectURL = URL.createObjectURL(myBlob);
16   myImage.src = objectURL;
17 });

  6.Headers消息头

  根据自己的需要设置消息头

  

1 var content = "Hello World";
2 var myHeaders = new Headers();
3 myHeaders.append("Content-Type", "text/plain");
4 myHeaders.append("Content-Length", content.length.toString());
5 myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

  另一种方式通过构造 函数的形式:

  

1 myHeaders = new Headers({
2   "Content-Type": "text/plain",
3   "Content-Length": content.length.toString(),
4   "X-Custom-Header": "ProcessThisImmediately",
5 });

  也可以查询或者删除

  

 1 console.log(myHeaders.has("Content-Type")); // true
 2 console.log(myHeaders.has("Set-Cookie")); // false
 3 myHeaders.set("Content-Type", "text/html");
 4 myHeaders.append("X-Custom-Header", "AnotherValue");
 5
 6 console.log(myHeaders.get("Content-Length")); // 11
 7 console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
 8
 9 myHeaders.delete("X-Custom-Header");
10 console.log(myHeaders.getAll("X-Custom-Header")); // [ ]

  如果消息头的类型不存在会抛出类型异常,所有使用之前可以先检查

 1 var myResponse = Response.error();
 2 try {
 3   myResponse.headers.set("Origin", "http://mybank.com");
 4 } catch(e) {
 5   console.log("Cannot pretend to be a bank!");
 6 }
 7
 8
 9
10
11 fetch(myRequest).then(function(response) {
12   var contentType = response.headers.get("content-type");
13   if(contentType && contentType.indexOf("application/json") !== -1) {
14     return response.json().then(function(json) {
15       // process your JSON further
16     });
17   } else {
18     console.log("Oops, we haven‘t got JSON!");
19   }
20 });

  7.监控

    可能监控的一些值

    

1 none: default.
2 request: guard for a headers object obtained from a request (Request.headers).
3 request-no-cors: guard for a headers object obtained from a request created with Request.mode no-cors.
4 response: guard for a Headers obtained from a response (Response.headers).
5 immutable: Mostly used for ServiceWorkers; renders a headers object read-only.

  8.Response objects

    用于当 fetch()返回的pormise是resolved时的操作.

    

1 var myBody = new Blob();
2
3 addEventListener(‘fetch‘, function(event) {
4   event.respondWith(new Response(myBody, {
5     headers: { "Content-Type" : "text/plain" }
6   });
7 });

  一些属性:

  

1 Response.status — An integer (default value 200) containing the response status code.
2 Response.statusText — A string (default value "OK"),which corresponds to the HTTP status code message.
3 Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean.

  9.Body

  消息内容

  request或者response都可能有body data,可能有下面的一些格式:

  

1 ArrayBuffer
2 ArrayBufferView (Uint8Array and friends)
3 Blob/File
4 string
5 URLSearchParams
6 FormData

  定义一下一些方法去提取body(在Request和Response中被实现)

  

1 arrayBuffer()
2 blob()
3 json()
4 text()
5 formData()

文档

时间: 2024-08-07 23:40:35

fetch API的相关文章

(转)这个API很“迷人”——新的Fetch API

原文:https://hacks.mozilla.org/2015/03/this-api-is-so-fetching 原标题是This API is So Fetching,Fetching也可以表示迷人的意思——译者注 JavaScript 通过XMLHttpRequest(XHR)来执行异步请求,这个方式已经存在了很长一段时间.虽说它很有用,但它不是最佳API.它在设计上不符合职责分离原则,将输入.输出和用事件来跟踪的状态混杂在一个对象里.而且,基于事件的模型与最近JavaScript流

Ajax新玩法fetch API

目前 Web 异步应用都是基于 XMLHttpRequest/ActiveXObject (IE)实现的, 这些对象不是专门为资源获取而设计的,因而它们的 API 非常复杂,同时还需要开发者处理兼容性问题. 虽然开发者普遍使用 $.ajax() 这样的上层包装,但 Fetch API 意在提供更加方便和一致的原生 API, 同时统一 Web 平台上的资源获取行为,包括外链脚本.样式.图片.AJAX 等.同时Fetch API使用Promise,因此是一种简洁明了的API,比XMLHttpRequ

基于Promise规范的fetch API的使用

基于Promise规范的fetch API的使用 fetch的使用 作用:fetch 这个API,是专门用来发起Ajax请求的: fetch 是由原生 JS 提供的 API ,专门用来取代 XHR 这个对象的: fetch('请求的url地址').then(response => res.json()).then(data= > console.log(data)) // 注意: 第一个.then 中获取到的不是最终的数据,而是一个中间的数据流对象: // 注意: 第一个 .then 中获取到

ES6 Fetch API HTTP请求实用指南

本次将介绍如何使用Fetch API(ES6 +)对REST API的 HTTP请求,还有一些示例提供给大家便于大家理解. 注意:所有示例均在带有箭头功能的 ES6中给出. 当前的Web /移动应用程序中的一种常见模式是从服务器请求或显示某种数据(例如用户,帖子,评论,订阅,付款等),然后使用CRUD(创建-Create,阅读-Retrieve,更新-Update或删除-Delete)操作. 为了进一步操作资源,我们经常使用这些JS方法(推荐),例如 .map(), .filter()和 .re

[Javascript] Fetch API

fetch() does the same thing as XHR, but fetch return a promise. fetch('password.txt', { 'method': 'PUT', 'headers': { 'X-Something-nothing': 'fetch rocks!' } }).then( response => { if(response.status === 200){ return response.text() }else{ throw "

React + fetch API + 百度地图api + 跨域 填坑

做项目遇到一个百度地图api 的跨域问题.由于使用fetch ,在调用类似 http://api.map.baidu.com/geocoder/v2/callback=renderReverse&location=39.983424,116.322987&output=json&pois=1&ak=您的ak 的时候,不可避免的出现了跨域问题. fetch(baseUrl + 'location=39,116&output=json&ak=您的ak&c

如何理解 RxJS?RxJS的中文API和使用教程

如何理解 RxJS? 我先附上RxJS的中文教程地址方便大家去了解和使用 中文使用教程:http://rxjs-china.org/_book/ 官方中文文档:https://buctwbzs.gitbooks.io/rxjs/content/ 好啦,我们开始讲一下如何理解它 RxJS 可能对很多人而言是一个从没听说过的新名词,那么 RxJS 到底是什么呢?本文中将予以简要介绍 在 Angular 2 中,我们遇到了一个新的概念 —— RxJS. 对很多人而言,这可能是一个比较难以理解的地方.所

fetch 报错 Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body. 在"窗口"上执行"取"失败:GET / get方法的请求不能有正文. GET requests can't have a request body, you can't make them have one. GET requests only retrieve data,

[转] 传统 Ajax 已死,Fetch 永生

原谅我做一次标题党,Ajax 不会死,传统 Ajax 指的是 XMLHttpRequest(XHR),未来现在已被 Fetch 替代. 最近把阿里一个千万级 PV 的数据产品全部由 jQuery 的 $.ajax 迁移到 Fetch,上线一个多月以来运行非常稳定.结果证明,对于 IE8+ 以上浏览器,在生产环境使用 Fetch 是可行的. 由于 Fetch API 是基于 Promise 设计,有必要先学习一下 Promise,推荐阅读 MDN Promise 教程.旧浏览器不支持 Promis