一.什么是fetch?

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

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

  还不是很强.

二.如何使用fetch?

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

  GlobalFetch:

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

  Headers:

    表示response/request的消息头

  Request:

    用于请求资源

  Response:

    一个request的响应消息

  Body

    消息的内容

三.开始使用fetch

  1.检查兼容性

    

 if(self.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
}

  2.发送一个请求

  

 var myImage = document.querySelector('img');

 fetch('flowers.jpg')
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});

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

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

  

 var myHeaders = new Headers();

 var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' }; fetch('flowers.jpg',myInit)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});

  4.检查请求是否成功

  

 fetch('flowers.jpg').then(function(response) {
if(response.ok) {
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
console.log('Network response was not ok.');
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});

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

  

 var myHeaders = new Headers();

 var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' }; var myRequest = new Request('flowers.jpg',myInit); fetch(myRequest,myInit)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});

  6.Headers消息头

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

  

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

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

  

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

  也可以查询或者删除

  

 console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue"); console.log(myHeaders.get("Content-Length")); //
console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]

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

 var myResponse = Response.error();
try {
myResponse.headers.set("Origin", "http://mybank.com");
} catch(e) {
console.log("Cannot pretend to be a bank!");
} fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(function(json) {
// process your JSON further
});
} else {
console.log("Oops, we haven't got JSON!");
}
});

  7.监控

    可能监控的一些值

    

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

  8.Response objects

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

    

 var myBody = new Blob();

 addEventListener('fetch', function(event) {
event.respondWith(new Response(myBody, {
headers: { "Content-Type" : "text/plain" }
});
});

  一些属性:

  

 Response.status — An integer (default value 200) containing the response status code.
Response.statusText — A string (default value "OK"),which corresponds to the HTTP status code message.
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,可能有下面的一些格式:

  

 ArrayBuffer
ArrayBufferView (Uint8Array and friends)
Blob/File
string
URLSearchParams
FormData

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

  

 arrayBuffer()
blob()
json()
text()
formData()

文档

fetch API的更多相关文章

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

    原文:https://hacks.mozilla.org/2015/03/this-api-is-so-fetching 原标题是This API is So Fetching,Fetching也可以 ...

  2. Ajax新玩法fetch API

    目前 Web 异步应用都是基于 XMLHttpRequest/ActiveXObject (IE)实现的, 这些对象不是专门为资源获取而设计的,因而它们的 API 非常复杂,同时还需要开发者处理兼容性 ...

  3. Fetch API & Async Await

    Fetch API & Async Await const fetchJSON = (url = ``) => { return fetch(url, { method: "G ...

  4. Fetch API & Delete & HTTP Methods

    Fetch API & Delete & HTTP Methods vue https://developer.mozilla.org/en-US/docs/Web/API/Fetch ...

  5. 解决React Native使用Fetch API请求网络报Network request failed

    问题来源: 1 . 在测试fetch数据请求时,Xcode9.0以上的无法请求https, 需要在Xcode中加载项目后修改Info.plist的相关配置,具体如下参考 问题及解决方法一模一样,不再重 ...

  6. 使用Vue cli3搭建一个用Fetch Api的组件

    系列参考 ,英文原文参考 我的git代码: https://github.com/chentianwei411/Typeahead 目标: 建立一个输入关键字得到相关列表的组件,用Vuejs2和Fet ...

  7. 取消Fetch API请求

    如今,Fetch API已经成为现在浏览器异步网络请求的标准方法,但Fetch也是有弊端的,比如: Fetch还没有方法终止一个请求,而且Fetch无法检测上传进度 现在我们可以通过 AbortCon ...

  8. fetch API & upload file

    fetch API & upload file https://github.com/github/fetch/issues/89 https://stackoverflow.com/ques ...

  9. Fetch API 接口参考

    前言 Fetch API是新的ajax解决方案,用于解决古老的XHR对象不能实现的问题,Fetch API 提供了一个获取资源的接口(包括跨域请求),任何使用过 XMLHttpRequest 的人都能 ...

  10. Cross-origin resource sharing JSON with Padding 同源策略 JSONP 为什么form表单提交没有跨域问题,但ajax提交有跨域问题? XMLHttpRequest and the Fetch API follow the same-origin policy 预检请求(preflight request)

    https://zh.wikipedia.org/wiki/跨来源资源共享 跨来源资源共享(CORS)是一份浏览器技术的规范,提供了 Web 服务从不同域传来沙盒脚本的方法,以避开浏览器的同源策略[1 ...

随机推荐

  1. tcp/IP点对点通信程序

    点对点的通信 服务器端与客户端在建立连接之后创建一个进程 服务器端: 子进程用于接收主机的输入并将数据发送出去.父进程用于接收客户端的数据并输出到主机. 子进程一直等待主机的输入,输入的数据放在发送缓 ...

  2. TexBox的属性

    允许多行输入

  3. net发送邮件

    对于.NET而言,从2.0开始,发邮件已经是一件非常easy 的事了.下面我给出一个用C#群发邮件的实例,做了比较详细的注解,希望对有需要的朋友有所help.看了这篇BLOG,如果你还不会用.NET发 ...

  4. Apple Swift中英文开发资源集锦[apple swift resources]

    找到的一些Apple Swift中英文资源原文链接,希望对大家有所帮助.欢迎大家补充,原始资源链接最好! The Swift Programming Language https://develope ...

  5. php 301

    2013年7月1日 13:35:45 PHP在301跳转的时候,如果是跨域跳转,记着把要跳转到的URL添上"http://"

  6. 利用 ffmpeg + ImageMagick + 批处理 生成高品质gif动画

    这几天研究如何生成高品质 gif 动画,重新研究 ffmpeg, 目前有一些自动转换工具,效果不佳. Video_to_320x180.bat 把 out.avi 转换成320x180的 01.avi ...

  7. google maps js v3 api教程(2) -- 在地图上添加标记

    原文链接 google maps javascript官方文档:https://developers.google.com/maps/documentation/javascript/ 我们在创建地图 ...

  8. 使用Memory Analyzer tool(MAT)分析内存泄漏(一)

    转载自:http://www.blogjava.net/rosen/archive/2010/05/21/321575.html 前言 在平时工作过程中,有时会遇到OutOfMemoryError,我 ...

  9. oracle 10g 学习之多表查询、分组函数(6)

    笛卡尔集 l  笛卡尔集会在下面条件下产生: 省略连接条件 连接条件无效 所有表中的所有行互相连接 l  为了避免笛卡尔集, 可以在 WHERE 加入有效的连接条件. 自连接 select m.las ...

  10. 2.Abstract Factory 抽象工厂(创建型模式)之简单工厂

    简单工厂 1.只有一个工厂(具体的,没有抽象) 2.只生产一种产品(抽象的产品) 3.这种产品可以有多种具体产品类型(派生) 代码实现 class Program { static void Main ...