fetch

1. fetch 简介

Fetch 等同于 XMLHttpRequest。它提供了许多与XMLHttpRequest相同的功能,但更具可扩展性和高效性。
Fetch 的核心在于对 HTTP 接口的抽象,包括 Request,Response,Headers,Body,以及用于初始化异步请求的 global fetch。得益于 JavaScript 实现的这些抽象好的 HTTP 模块,其他接口能够很方便的使用这些功能。
除此之外,Fetch 还利用到了请求的异步特性——它是基于 Promise 的。

2. 使用fetch

目前Chrome浏览器已经全局支持了fetch。可以通过下面的代码实现浏览器兼容问题:

1
2
3
4
5
if( self.fetch ){
// 使用fetch 处理
} else {
// 使用XMLHttpRequest或者其他分装框架处理
}

3. 一般构造请求方法

使用 fetch 的构造函数请求数据后,返回一个 Promise 对象,然后进行处理即可,代码如下:

1
2
3
fetch( url).then( function( response ){
// do some thing...
});

4. fetch 请求时进行配置项的配置

如果每次请求不受缓存的影响,则可以在请求头中进行如下配置:

1
2
3
4
5
6
7
fetch( url, {
headers: {
'Cache-Control': 'no-cache'
}
}).then(function( response ){
// do some thing...
})

更多的头部参数配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

var header = new Headers();
header.append("Content-Type", "text/plain");
header.append("Content-Length", content.length.toString());
header.append("X-Custom-Header","ProcessThisImmediately");

var options = {
headers: header,
method: 'GET',
mode: 'cors',
cache: 'default'
};

fetch( url, options ).then(function( response ){
// do some thing...
})

5. fetch返回的数据结构

在请求后的Response中,具体参数的一些定义:

Response.status : 整数(默认值为200)为response的状态码;
Response.statusText : 字符串(默认值为ok),该值与HTTP状态码消息对应;
Response.ok 该属性是来检查response的状态是否在200-299(包括200,299)这个范围内.该属性返回一个Boolean值.

1
2
3
4
5
fetch( url ).then( function( response ){
console.log( response.status );
console.log( response.statusText );
console.log( response.ok );
})

6. Body 参数

因为在 Request 和 Response 中都包含 Body 的实现,所以包含以下类型:

ArrayBuffer : 类型化数组
ArrayBufferView (Uint8Array and friends)
Blob/File
string
URLSearchParams
FormData

在 fetch 中实现了对应的方法,并返回的都是 Promise 类型,分别是:

arrayBuffer()
blob()
json()
text()
formData()
这样处理返回的数据类型就会变的特别地方便,如处理 json 格式的数据:

1
2
3
4
5
6
7
fetch( url ).then( function( response ){
return response.json().then( function( json ){
for( var i = 0; i < json.products.length; i++ ){
// do some thing...
}
})
})




[参考资料]:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!