在前端快速发展地过程中,为了契合更好的设计模式,产生了 fetch 框架,此文将简要介绍下 fetch 的基本使用。
在 AJAX 时代,进行请求 API 等网络请求都是通过 XMLHttpRequest 或者封装后的框架进行网络请求。
现在产生的 fetch 框架简直就是为了提供更加强大、高效的网络请求而生,虽然在目前会有一点浏览器兼容的问题,但是当我们进行 Hybrid App 开发的时候,如我之前介绍的Ionic 和React Native,都可以使用 fetch 进行完美的网络请求。
fetch 初体验
在 Chrome 浏览器中已经全局支持了 fetch 函数,打开调试工具,在 Console 中可以进行初体验。先不考虑跨域请求的使用方法,我们先请求同域的资源,如在我的博客页面中,打开 Console 进行如下请求。
fetch("http://blog.parryqiu.com").then(function(response){console.log(response)})
返回的数据:

这样就很快速地完成了一次网络请求,我们发现返回的数据也比之前的 XMLHttpRequest 丰富、易用的多。
关于 fetch 标准概览
虽然 fetch 还不是作为一个稳定的标准发布,但是在其一直迭代更新的 标准描述 中,我们发现已经包含了很多的好东西。
fetch 支持了大部分常用的 HTTP 的请求以及和 HTTP 标准的兼容,如 HTTP Method,HTTP Headers,Request,Response。
fetch 的使用
fetch的入口函数定义在node_modules/whatwg-fetch.js文件中,如下
self.fetch = function (input, init) {
return new Promise(function (resolve, reject) {
var request = new Request(input, init)
var xhr = new XMLHttpRequest()
xhr.onload = function () {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
}
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
var body = 'response' in xhr ? xhr.response : xhr.responseText
resolve(new Response(body, options))
}
xhr.onerror = function () {
reject(new TypeError('Network request failed'))
}
xhr.ontimeout = function () {
reject(new TypeError('Network request failed888888888888'))
}
xhr.open(request.method, request.url, true)
if (request.credentials === 'include') {
xhr.withCredentials = true
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob'
}
request.headers.forEach(function (value, name) {
xhr.setRequestHeader(name, value)
})
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
})
}
该函数在Network/fetch.js中被导出,最终在initializeCore.js中被注册为global的属性变为全局函数。fetch返回的是一个Promise。
