fecth 使用说明

安装与引入

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) {
// handle HTTP response
}, function(error) {
// handle network 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 //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url //=> String

response.text().then(function(responseText) { ... })
}, function(error) {
error.message //=> String
})

url

定义要获取的资源。这可能是:

  • 一个 USVString字符串,包含要获取资源的 URL
  • 一个 Request 对象。

    options(可选)

    一个配置项对象,包括所有对请求的设置。可选的参数有:

  • method: 请求使用的方法,如 GETPOST

  • headers: 请求的头信息,形式为 Headers 对象或 ByteString
  • body: 请求的 body 信息:可能是一个 BlobBufferSourceFormDataURLSearchParams 或者 USVString 对象。注意 GETHEAD 方法的请求不能包含 body 信息。
  • mode: 请求的模式,如 corsno-cors 或者 same-origin
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include
  • cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached

    response

    一个 Promiseresolve 时回传 Response 对象:
  • 属性:
    • 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()

      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
6
fetch('/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
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;
});
  • JSON
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
  • 引入 Promisepolyfill: es6-promise
  • 引入fetch 探测库:fetch-detector
  • 引入 fetchpolyfill: fetch-ie8
  • 可选:如果你还使用了 jsonp,引入 fetch-jsonp
  • 可选:开启 Babelruntime 模式,现在就使用 async/await

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 安装与引入
  2. 2. 语法说明
    1. 2.1. url
    2. 2.2. options(可选)
    3. 2.3. response
    4. 2.4. response.headers
  3. 3. 使用案例
    1. 3.1. GET请求
    2. 3.2. POST请求
    3. 3.3. Post form
    4. 3.4. Post JSON
    5. 3.5. File upload
  4. 4. 支持状况及解决方案
,