安装与引入 1 2 3 4 5 npm install whatwg-fetch --save; or bower install fetch. import 'whatwg-fetch'
语法说明 1 2 3 4 5 fetch(url, options).then(function (response ) { }, function (error ) { })
具体参数案例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 response.statusText response.headers response.url response.text().then(function(responseText) { ... }) }, function(error) { error.message })
url 定义要获取的资源。这可能是:
属性:
status (number)
- HTTP请求结果参数,在100–599 范围
statusText (String)
- 服务器返回的状态报告
ok (boolean)
- 如果返回200表示请求成功则为true
headers (Headers)
- 返回头部信息,下面详细介绍
url (String)
- 请求的地址
方法:
text()
- 以string
的形式生成请求text
json()
- 生成JSON.parse(responseText)
的结果
blob()
- 生成一个Blob
arrayBuffer()
- 生成一个ArrayBuffer
formData()
- 生成格式化的数据,可用于其他的请求
其他方法:
clone()
Response.error()
Response.redirect()
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 6 fetch('/users.html' ) .then (function (response) { return response.text() }).then (function (body) { document.body.innerHTML = body })
1 2 3 4 5 6 7 8 9 10 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; });
1 2 3 4 5 6 7 8 fetch(url) .then (function (response) { return response.json(); }).then (function (data) { console.log (data); }).catch (function (e) { console.log ("Oops, error" ); });
POST请求 1 2 3 4 5 6 7 8 9 10 11 fetch ('/users' , { method : 'POST' , headers : { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' }, body : JSON.stringify({ name : 'Hubot' , login : 'hubot' , }) })
Post form 1 2 3 4 5 6 var form = document.querySelector('form' ) fetch('/users' , { method: 'POST' , body : new FormData(form) })
Post JSON 1 2 3 4 5 6 7 8 9 10 fetch ('/users' , { method : 'POST' , headers : { 'Content-Type' : 'application/json' }, body : JSON.stringify({ name : 'Hubot' , login : 'hubot' , }) })
File upload 1 2 3 4 5 6 7 8 9 10 var input = document.querySelector('input[type="file"]' ) var data = new FormData()data.append('file' , input .files [0 ]) data.append('user' , 'hubot' ) fetch('/avatars' , { method: 'POST' , body : 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
<
Redux