Fetch API

Ajax 的 API -> fetch():

一起学习吧:http://javascript.ruanyifeng.com/bom/ajax.html#toc27

fetch操作返回Promise对象,babel可以编译,一些高版本浏览器支持。

fetch(url).then(function (response) {
  return response.json();
}).then(function (jsonData) {
  console.log(jsonData);
}).catch(function () {
  console.log('出错了');
});

对比XHR写法

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
  console.log(xhr.response);
};
xhr.onerror = function() {
  console.log('出错了');
};
xhr.send();

Fetch API提供以下五个数据流读取器:

response.text():返回字符串。

response.json():返回一个JSON对象。

response.formData():返回一个FormData对象。

response.blob():返回一个对象。

response.arrayBuffer():返回一个二进制数组。

数据流只能读取一次,一旦读取,数据流变空,再次读取会报错。

可以使用response.clone()复制一个副本。

var progress = 0;
var contentLength = 0;

var getStream = function (reader) {
  return reader.read().then(function (result) {
    // 如果数据已经读取完毕,直接返回
    if (result.done) {
      return;
    }

    // 取出本段数据(二进制格式)
    var chunk = result.value;

    var text = '';
    // 假定数据是UTF-8编码,前三字节是数据头,
    // 而且每个字符占据一个字节(即都为英文字符)
    for (var i = 3; i < chunk.byteLength; i++) {
      text += String.fromCharCode(chunk[i]);
    }

    // 将本段数据追加到网页之中
    document.getElementById('content').innerHTML += text;

    // 计算当前进度
    progress += chunk.byteLength;
    console.log(((progress / contentLength) * 100) + '%');

    // 递归处理下一段数据
    return getStream(reader);
  };
};

fetch():

第一个参数:可以是url也可以是Request对象实例。Fetch函数返回一个Promise对象,并将一个response对象传给回调函数。

第二个参数:是一个option对象,用于配置请求方式,发不发送数据给服务器,采不采用跨域方式:

1、mode:值有,basic正常同域请求,cors在CORS机制下跨域请求,opaque非CORS机制下跨域请求。

2、credentials:是否将cookie发送到服务器端,发送"include"

3、mothod:"POST" "GET"

4、headers:{"Cache-Control":"publice,24*60*60,"}

5、body:要传到后台的数据,可以接受blob、formData、字符串(key1=value1&key2=value2) 包括图片和文件

Fetch API 引入三个新对象 Headers Request Response 也是构造函数 new Headers() new Request() new Response()

使用方法和FormData对象很像

var content = 'Hello World';
var headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Content-Type", "text/plain");
headers.append("Content-Length", content.length.toString());
headers.append("X-Custom-Header", "ProcessThisImmediately");
reqHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});
reqHeaders.has("Content-Type") // true
reqHeaders.has("Set-Cookie") // false
reqHeaders.set("Content-Type", "text/html")
reqHeaders.append("X-Custom-Header", "AnotherValue")

reqHeaders.get("Content-Length") // 11
reqHeaders.getAll("X-Custom-Header") // ["ProcessThisImmediately", "AnotherValue"]

reqHeaders.delete("X-Custom-Header")
reqHeaders.getAll("X-Custom-Header") // []

Headers 可以配合 Request 或者 Response

var headers = new Headers({
  'Content-Type': 'application/json',
  'Cache-Control': 'max-age=3600'
});

var response = new Response(
  JSON.stringify({photos: {photo: []}}),
  {'status': 200, headers: headers}
);

response.json().then(function(json) {
  insertPhotos(json);
});
var headers = new Headers();
headers.append('Accept', 'application/json');
var request = new Request(URL, {headers: headers});

fetch(request).then(function(response) {
  console.log(response.headers);
});

Request对象:Request对象用来构造HTTP请求

var uploadReq = new Request("/uploadImage", {
  method: "POST",
  headers: {
    "Content-Type": "image/png",
  },
  body: "image data"
});
var req = new Request("/index.html");
req.method // "GET"
req.url // "http://example.com/index.html"
var req = new Request(URL, {method: 'GET', cache: 'reload'});
fetch(req).then(function(response) {
  return response.json();
}).then(function(json) {
  someOperator(json);
});

fetch方法返回Response对象实例,它有以下属性。

  • status:整数值,表示状态码(比如200)
  • statusText:字符串,表示状态信息,默认是“OK”
  • ok:布尔值,表示状态码是否在200-299的范围内
  • headers:Headers对象,表示HTTP回应的头信息
  • url:字符串,表示HTTP请求的网址
  • type:字符串,合法的值有五个basic、cors、default、error、opaque。basic表示正常的同域请求;cors表示CORS机制的跨域请求;error表示网络出错,无法取得信息,status属性为0,headers属性为空,并且导致fetch函数返回Promise对象被拒绝;opaque表示非CORS机制的跨域请求,受到严格限制。
    • Response.error() 返回一个type属性为error的Response对象实例
    • Response.redirect(url, status) 返回的Response对象实例会重定向到另一个URL
    • fetch("https://example.com", init)
      .then(function (response) {
      // Check that the response is a 200
        if (response.status === 200) {
          alert("Content type: " + response.headers.get('Content-Type'));
        }
      });

      Request对象和Response对象都有body属性,表示请求的内容。body属性可能是以下的数据类型:

      • ArrayBuffer
      • ArrayBufferView (Uint8Array等)
      • Blob/File
      • string
      • URLSearchParams
      • FormData
      • Request对象和Response对象都提供以下方法,用来读取body。
        • arrayBuffer()
        • blob()
        • json()
        • text()
        • formData()
        • Request对象和Response对象都有bodyUsed属性,返回一个布尔值,表示body是否被读取过
原文地址:https://www.cnblogs.com/lantuoxie/p/6954067.html