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 }
View Code

   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 });
View Code

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

  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 });
View Code

  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 });
View Code

  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 });
View Code

  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");
View Code

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

  

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

  也可以查询或者删除

  

 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")); // [ ]
View Code

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

 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 });
View Code

  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.
View Code

  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 });
View Code

  一些属性:

  

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.
View Code

  9.Body

  消息内容

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

  

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

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

  

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

    文档

posted @ 2016-04-10 23:36  我想我是海~~  阅读(838)  评论(0编辑  收藏  举报