由于 Fetch
API 是基于 Promise
设计,有必要先学习一下 Promise
,推荐阅读 MDN Promise 教程
本文章内容推荐阅读 MDN Fetch 教程
语法说明
1 | fetch(url, options).then(function(response) { |
具体参数案例:
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
。
response
一个 Promise
,resolve
时回传 Response
对象:
- 属性:
status (number)
- HTTP 请求结果参数,在 100–599 范围statusText (String)
- 服务器返回的状态报告ok (boolean)
- 如果返回 200 表示请求成功则为 trueheaders (Headers)
- 返回头部信息,下面详细介绍url (String)
- 请求的地址
- 方法:
text()
- 以string
的形式生成请求 textjson()
- 生成JSON.parse(responseText)
的结果blob()
- 生成一个Blob
arrayBuffer()
- 生成一个ArrayBuffer
formData()
- 生成格式化的数据,可用于其他的请求
- 其他方法:
clone()
Response.error()
Response.redirect()
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 的信息
使用案例
GET 请求
HTML
1
2
3
4
5
6fetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
})IMAGE
1
2
3
4
5
6
7
8
9
10var 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
1
2
3
4
5
6
7
8fetch(url)
.then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});使用 ES6 的 箭头函数 后:
1
2
3
4fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))response 的数据
1
2
3
4
5
6fetch('/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 请求
1 | fetch('/users', { |
检查请求状态
1 | function checkStatus(response) { |
采用 promise 形式
Promise 对象是一个返回值的代理,这个返回值在 promise 对象创建时未必已知。它允许你为异步操作的成功或失败指定处理方法。 这使得异步方法可以像同步方法那样返回值:异步方法会返回一个包含了原返回值的 promise 对象来替代原返回值。
Promise 构造函数接受一个函数作为参数,该函数的两个参数分别是resolve
方法和reject
方法。如果异步操作成功,则用resolve
方法将Promise
对象的状态变为“成功”(即从 pending 变为 resolved);如果异步操作失败,则用 reject 方法将状态变为“失败”(即从 pending 变为 rejected)。
promise 实例生成以后,可以用 then 方法分别指定 resolve 方法和 reject 方法的回调函数。
1 | //创建一个promise对象 |
那么结合 promise 后 fetch 的用法:
1 | //Fetch.js |
调用 Fech 方法:
1 | import { Fetch } from './Fetch' |
支持状况及解决方案
原生支持率并不高,幸运的是,引入下面这些 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
翻译自 Fetch