事实标准,并不存在与ES6规范中,基于Promise实现。
目前项目中对Promise的兼容性尚存在问题,若是在项目中应用fetch,须要引入es6-promise和fetch。
fis3中能够经过fis3 install es6-promise
和fis3 install fetch
进行安装。
如下提到为了浏览器兼容而引入的fech组件时统一使用'fech组件'代替。
该文档重点针对fetch组件进行详细说明。git
fetch('/test/content.json').then(function(data){ return data.json(); }).then(function(data){ console.log(data); }).catch(function(error){ console.log(error); });
fetch('/test/content.json', { // url: fetch事实标准中能够经过Request相关api进行设置 method: 'POST', mode: 'same-origin', // same-origin|no-cors(默认)|cors credentials: 'include', // omit(默认,不带cookie)|same-origin(同源带cookie)|include(老是带cookie) headers: { // headers: fetch事实标准中能够经过Header相关api进行设置 'Content-Type': 'application/x-www-form-urlencoded' // default: 'application/json' }, body: 'a=1&b=2' // body: fetch事实标准中能够经过Body相关api进行设置 }).then(function(res){ res: fetch事实标准中能够经过Response相关api进行设置 return res.json(); }).then(function(data){ console.log(data); }).catch(function(error){ });
fetch('/test/content.json').then(function(res){ console.log(res.bodyUsed); // false var data = res.json(); console.log(res.bodyUsed); //true return data; }).then(function(data){ console.log(data); }).catch(function(error){ console.log(error); });
fetch('/test/content.json').then(function(res){ var headers = res.headers; console.log(headers.get('Content-Type')); // application/json console.log(headers.has('Content-Type')); // true console.log(headers.getAll('Content-Type')); // ["application/json"] for(let key of headers.keys()){ console.log(key); // datelast-modified server accept-ranges etag content-length content-type } for(let value of headers.values()){ console.log(value); } headers.forEach(function(value, key, arr){ console.log(value); // 对应values()的返回值 console.log(key); // 对应keys()的返回值 }); return res.json(); }).then(function(data){ console.log(data); }).catch(function(error){ console.log(error); });
200-299
之间basic
:正常的,同域的请求,包含全部的headers。排除Set-Cookie
和Set-Cookie2
。cors
:Response从一个合法的跨域请求得到,一部分header和body可读。error
:网络错误。Response的status是0,Headers是空的而且不可写。当Response是从Response.error()中获得时,就是这种类型。opaque
: Response从"no-cors"请求了跨域资源。依靠Server端来作限制。fetch('/test/content.json').then(function(data){ var d = data.clone(); d.text().then(function(text){ console.log(JSON.parse(text)); }); return data.json(); }).then(function(data){ console.log(data); }).catch(function(error){ console.log(error); });