什么是Fetch
一句话总结:Fetch是XMLHttpRequest一个更先进的替代方案(A Modern Replacement for XMLHttpRequest)。
fetch是全局变量window的一个方法,用来发起网络请求、获取资源,是传统基于XMLHttpRequest对象的AJAX技术的更优替代方案。
fetch暂时不支持abort request。
使用方法
先看一个最简单的get用法示例:
// url (required), options (optional)
fetch(‘https://davidwalsh.name/some/url’, {
method: ‘get’
}).then(function(response) {
}).catch(function(err) {
// Error 🙁
});
下面是一个稍微复杂的post用法示例:
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
return response.text()
}, function(error) {
error.message //=> String
})
fetch使用Promises来处理response。fetch接收两个参数:
url:string类型,必选,发起请求的地址
options:object类型,可选,请求的配置参数
还可以使用Request对象实例作为参数的方式发起fetch请求:
var request = new Request(url, options);
fetch(request).then(function(response) {
// handle with response…
}).catch(function(err) {
// Error 🙁
});
Options配置项
options可以配置以下参数:
1.method (String) – HTTP 请求方法,默认:”GET”
2.body (String, body types) – HTTP 请求主体,示例:
{
body: new URLSearchParams([[‘foo’, 1], [‘bar’, 2]]).toString()
}
body的类型包括:
Class
Default Content-Type
String
text/plain;charset=UTF-8
URLSearchParams
application/x-www-form-urlencoded;charset=UTF-8
FormData
multipart/form-data
Blob
inherited from the blob.type property
ArrayBuffer
TypedArray
DataView
其他数据结构需要预先编码为上述类型之一。例如,JSON.stringify(data)可用于将数据结构序列化为JSON字符串。
3.headers (Object, Headers) – 请求头,默认:{},示例:
{
headers: new Headers({
‘Content-Type’: ‘application/x-www-form-urlencoded’ // 指定提交方式为表单提交
})
}
headers提供以下方法增删改查头部信息:
has(name) (boolean)
get(name) (String)
set(name, value)
append(name, value)
delete(name)
forEach(function(value, name){ … }, [thisContext])
4.credentials (String) – 跨域请求时方身份验证凭证模式,默认:”omit”
“omit” – 请求中不携带身份验证凭证(例如cookies)
“same-origin” – 在对同一站点的请求中包含身份验证凭证
“include” – 在所有站点的请求中包含身份验证凭证
响应结果Response
Response表示来自服务器的HTTP响应。Response会作为promise回调函数的参数。 包含以下属性:
status (number) – HTTP状态码,范围在100–599之内
statusText (String) – 响应文本,如:”Unauthorized”
ok (boolean) – status为2xx时表示响应成功,值为true
headers (Headers)
url (String)
此外,response还提供了一些方法处理成特定的数据格式并返回一个Promise:
text() – 以字符串形式生成响应文本
json() – 生成JSON.parse(responseText)的结果
blob() – 生成一个Blob
arrayBuffer() – 生成一个ArrayBuffer
formData() – 生成可转发到另一个请求的表单数据
示例:
response.blob().then(function(myBlob) {
// do something with myBlob
});
错误处理
如果出现网络错误或其他原因导致HTTP请求无法完成,fetch()的promise 将会reject该error。
注意,在HTTP 4xx或5xx服务器响应的情况下,promise不会reject。这个promise将像HTTP 2xx一样正常resolve。可以通过检查response.status的状态码来决定如何处理错误:
fetch(…).then(function(response) {
if (response.ok) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
})
兼容情况
截至目前,fetch的浏览器兼容情况如下图所示:
(可以在can I use这个网站查询浏览器兼容性)
如果想要兼容IE及老版本浏览器,可以使用polyfill:whatwg-fetch
Renerence
1.https://github.github.io/fetch/
2.http://louiszhai.github.io/2016/11/02/fetch/
3.https://juejin.im/entry/574512b7c26a38006c43567c
4.https://davidwalsh.name/fetch