fetch() 是 window.fetch 的 javascript polyfill。
全局 fetch()
函数是 web 请求和处理响应的简单方式,不使用 xmlhttprequest。这个 polyfill 编写的接近标准的 fetch 规范。
fetch()是xmlhttprequest的升级版,用于在javascript脚本里面发出 http 请求。
fetch()的功能与 xmlhttprequest 基本相同,但有三个主要的差异。
(1)fetch()使用 promise,不使用回调函数,因此大大简化了写法,写起来更简洁。
(2)采用模块化设计,api 分散在多个对象上(response 对象、request 对象、headers 对象),更合理一些;相比之下,xmlhttprequest 的 api 设计并不是很好,输入、输出、状态都在同一个接口管理,容易写出非常混乱的代码
(3)fetch()通过数据流(stream 对象)处理数据,可以分块读取,有利于提高网站性能表现,减少内存占用,对于请求大文件或者网速慢的场景相当有用。xmlhttprequest 对象不支持数据流,
所有的数据必须放在缓存里,不支持分块读取,必须等待全部拿到后,再一次性吐出来。在用法上接受一个 url 字符串作为参数,默认向该网址发出 get 请求,返回一个 promise 对象
fetch()函数支持所有的 http 方式:
获取html类型数据
fetch('/users.html') .then(function(response) { return response.text() }).then(function(body) { document.body.innerhtml = body })
获取json类型数据
fetch('/users.json') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) })
一:fetch()语法说明
fetch(url, options).then(function(response) { // handle http response }, function(error) { // handle network error })
具体参数案例:
require('babel-polyfill') require('es6-promise').polyfill() import 'whatwg-fetch' fetch(url, { method: "post", body: json.stringify(data), headers: { "content-type": "application/json" }, credentials: "same-origin" }).then(function(response) { response.status //=> number 100–599 response.statustext //=> string response.headers //=> headers response.url //=> string response.text().then(function(responsetext) { ... }) }, function(error) { error.message //=> string })
1.url定义要获取的资源。
这可能是:
• 一个 usvstring 字符串,包含要获取资源的 url。
• 一个 request 对象。
options(可选)
一个配置项对象,包括所有对请求的设置。可选的参数有:
• method: 请求使用的方法,如 get、post。
• headers: 请求的头信息,形式为 headers 对象或 bytestring。
• body: 请求的 body 信息:可能是一个 blob、buffersource、formdata、urlsearchparams 或者 usvstring 对象。注意 get 或 head 方法的请求不能包含 body 信息。
• mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
• credentials: 请求的 credentials,如 omit、same-origin 或者 include。
• cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached。
2.response一个 promise,resolve 时回传 response 对象:
• 属性:
o status (number) - http请求结果参数,在100–599 范围
o statustext (string) - 服务器返回的状态报告
o ok (boolean) - 如果返回200表示请求成功则为true
o headers (headers) - 返回头部信息,下面详细介绍
o url (string) - 请求的地址
• 方法:
o text() - 以string的形式生成请求text
o json() - 生成json.parse(responsetext)的结果
o blob() - 生成一个blob
o arraybuffer() - 生成一个arraybuffer
o formdata() - 生成格式化的数据,可用于其他的请求
• 其他方法:
o clone()
o response.error()
o response.redirect()
3.response.headers
• has(name) (boolean) - 判断是否存在该信息头
• get(name) (string) - 获取信息头的数据
• getall(name) (array) - 获取所有头部数据
• set(name, value) - 设置信息头的参数
• append(name, value) - 添加header的内容
• delete(name) - 删除header的信息
• foreach(function(value, name){ ... }, [thiscontext]) - 循环读取header的信息
二:具体使用案例
1.get请求
• html数据:
fetch('/users.html') .then(function(response) { return response.text() }).then(function(body) { document.body.innerhtml = body })
• image数据
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; });
• json数据
fetch(url) .then(function(response) { return response.json(); }).then(function(data) { console.log(data); }).catch(function(e) { console.log("oops, error"); });
使用 es6 的 箭头函数后:
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("oops, error", e))
response的数据
fetch('/users.json').then(function(response) { console.log(response.headers.get('content-type')) console.log(response.headers.get('date')) console.log(response.status) console.log(response.statustext) })
post请求
fetch('/users', { method: 'post', headers: { 'accept': 'application/json', 'content-type': 'application/json' }, body: json.stringify({ name: 'hubot', login: 'hubot', }) })
检查请求状态
function checkstatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new error(response.statustext) error.response = response throw error } } function parsejson(response) { return response.json() } fetch('/users') .then(checkstatus) .then(parsejson) .then(function(data) { console.log('request succeeded with json response', data) }).catch(function(error) { console.log('request failed', error) })
采用promise形式
promise 对象是一个返回值的代理,这个返回值在promise对象创建时未必已知。它允许你为异步操作的成功或失败指定处理方法。 这使得异步方法可以像同步方法那样返回值:异步方法会返回一个包含了原返回值的 promise 对象来替代原返回值。
promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve方法和reject方法。如果异步操作成功,则用resolve方法将promise对象的状态变为“成功”(即从pending变为resolved);如果异步操作失败,则用reject方法将状态变为“失败”(即从pending变为rejected)。
promise实例生成以后,可以用then方法分别指定resolve方法和reject方法的回调函数。
//创建一个promise对象 var promise = new promise(function(resolve, reject) { if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } }); //then方法可以接受两个回调函数作为参数。 //第一个回调函数是promise对象的状态变为resolved时调用,第二个回调函数是promise对象的状态变为reject时调用。 //其中,第二个函数是可选的,不一定要提供。这两个函数都接受promise对象传出的值作为参数。 promise.then(function(value) { // success }, function(value) { // failure });
那么结合promise后fetch的用法:
//fetch.js export function fetch(url, options) { options.body = json.stringify(options.body) const defer = new promise((resolve, reject) => { fetch(url, options) .then(response => { return response.json() }) .then(data => { if (data.code === 0) { resolve(data) //返回成功数据 } else { if (data.code === 401) { //失败后的一种状态 } else { //失败的另一种状态 } reject(data) //返回失败数据 } }) .catch(error => { //捕获异常 console.log(error.msg) reject() }) }) return defer }
调用fech方法:
import { fetch } from './fetch' fetch(getapi('search'), { method: 'post', options }) .then(data => { console.log(data) })
三:支持状况及解决方案
原生支持率并不高,幸运的是,引入下面这些 polyfill 后可以完美支持 ie8+ :
• 由于 ie8 是 es3,需要引入 es5 的 polyfill: es5-shim, es5-sham
• 引入 promise 的 polyfill: es6-promise
• 引入 fetch 探测库:fetch-detector
• 引入 fetch 的 polyfill: fetch-ie8
• 可选:如果你还使用了 jsonp,引入 fetch-jsonp
• 可选:开启 babel 的 runtime 模式,现在就使用 async/await
发表评论