什么是Fetch API
Fetch API提供了一个获取资源的接口,类似于XMLHttpRequest。
Fetch API中最基础的的一个接口是fetch()
:
let url = 'http://example.com';
fetch(url)
.then(res => res.json())
.catch(error => console.log(error))
除了提供了fetch()
这个函数,Fetch API还定义了相应的Request
和Response
API语法
Promise<Response> fetch(input[, init]);
参数
-
input
定义要获取的资源,可以是:
- 字符串,包含要获取资源的 URL
-
Request
对象
-
init
请求的配置项,可选参数如下:
-
method
: 请求使用的方法,如GET
、POST
。 -
headers
: 请求的头信息,形式为Headers
的对象或包含ByteString
值的对象字面量。 -
body
: 请求的body信息,可能是一个Blob
、BufferSource
、FormData
、URLSearchParams
或者USVString
对象。 -
mode
: 请求的模式,如cors
、no-cors
或者same-origin
。 -
credentials
: 请求的credentials
,如omit
、same-origin
或者include
。为了在当前域名内自动发送cookie
,必须提供这个选项。 -
cache
: 请求的cache
模式:default
、no-store
、reload
、no-cache
、force-cache
或者only-if-cached
。 -
redirect
: 可用的redirect
模式:follow
(自动重定向),error
(如果产生重定向将自动终止并且抛出一个错误), 或者manual
(手动处理重定向)。 -
referrer
: 一个USVString
可以是no-referrer
、client
或一个URL
。默认是client
。
返回值
Promise
,resolve
时回传Response
对象。
异常
-
AbortError
:请求被取消 -
TypeError
: 如果URL中有用户权限,例如:http://user:password@example.com
与ajax()
的不同
- 当服务端返回404或500时,
fetch()
返回的Promise
不会reject
,而是会resolve
,但是response.ok
的值会变成false
。当response的状态码是2XX
时,response.ok
的值会是true
。因此,在对response进行处理之前,需要先检查response.ok
。 - 默认情况下,
fetch()
发送请求时不会带上cookies
。要发送cookies
,必须设置credentials
选项,即第二个参数中的{credentials: 'include'}
。
为什么有了Fetch API
要回答这个问题,首先需要思考的是,没有Fetch API时用的是什么——Ajax,即对XMLHttpRequest的封装。
一般会这样使用XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
console.log(this.responseText);
} else {
console.log('There was a problem with the request.');
}
}
}
或者使用jquery:
$.ajax({
url: url,
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
而使用fetch()则会是这样:
fetch(url, {method: 'GET'})
.then(function(res){console.log(res.json())})
.catch(function(error){console.log(error)});
从以上示例代码中可以很直观的看出,fetchAPI至少有以下几个优点:
- 代码简洁直观。
- 可以链式调用。
总结
使用Promise API可以避免“回调地狱”。此外,fetch API对请求和响应都作了规范,使得在配置Request以及消费Response时使用的API更加直观。原生的XMLHttpRequest以及jquery都把所有的配置项揉合在一起,配置起来十分不方便。
当然,Fetch API也有缺陷,不支持取消请求。一旦发起,不能中断,也不会超时,只能等待被 resolve 或 reject。
另外,目前fetchAPI还存在部分兼容性的问题,要在生产环境中使用的话,需要使用ployfill。