(给前端大全加星标,提升前端技能)
英文:Flavio 译文:众成翻译/涯丨角 https:///article/understanding-the-fetch-api
介绍 Fetch API自从1998年发布IE5以来,浏览器中异步网络请求都是通过 XMLHttpRequest (XHR)。 这之后几年,Gmail等应用大量使用这种方法,使这种方法逐渐流行,并给它一个名字:AJAX。 直接使用XMLHttpRequest总是非常痛苦的,许多库都对这种方法进行了封装,特别地,jQuery封装的方法如下: jQuery.ajax() jQuery.get()
jQuery.post()
这些方法内部做了许多兼容性的处理,来使这些方法在那些较老版本的浏览器上仍能正常工作。 Fetch API 已经作为现代浏览器中异步网络请求的标准方法,其使用 Promise 作为基本构造要素。 Fetch 在主流浏览器中都有很好的支持,除了IE。 
GitHub 上有发布的polyfill https://github.com/github/fetch ,使fetch可以在任何浏览中使用。 使用FetchGET 请求中使用Fetch非常简单,如下: 上面这段代码表示,fetch 创建了一个 HTTP 请求,去本域下请求 file.json 资源。 正如你看到的,fetch函数可以在全局window作用域下使用。 现在,我们做些更有用的事,来看一看请求到的文件的内容: fetch('./file.json') .then(response => response.json()) .then(data => console.log(data))
fetch() 会返回一个 promise。然后我们用then()方法编写处理函数来处理promise中异步返回的结果。 处理函数会接收fetch promise的返回值,这是一个 Response 对象。 我们会在下一部分看到这个对象的细节。 捕获错误既然 fetch() 返回一个promise,我们可以用promise的catch来拦截在执行这个请求和then里面回调函数中发生的任何错误。 fetch('./file.json') .then(response => { //... }) .catch(err => console.error(err))
响应对象调用fetch()所返回的响应对象包含了所有关于这个网络请求的请求和响应信息。 元数据headersHTTP请求的头部信息可以通过访问响应对象的headers属性,如下所示: fetch('./file.json').then(response => { console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date')) })

status这个属性是一个整形数字,表示HTTP响应状态。 101, 204, 205, 或 304 代表没有响应体的状态
200 到 299 代表请求成功的状态
301, 302, 303, 307, 或 308 代表重定向的状态
fetch('./file.json').then(response => console.log(response.status))
statusTextstatusText 属性表示响应状态信息。如果请求成功,其值为'OK'。 fetch('./file.json').then(response => console.log(response.statusText))
urlurl 表示我们请求资源的全路径URL。 fetch('./file.json').then(response => console.log(response.url))
响应体响应会有响应体,可以通过 text() 或者 json() 方法来拿到,这会返回一个promise对象。 fetch('./file.json') .then(response => response.text()) .then(body => console.log(body))
fetch('./file.json') .then(response => response.json()) .then(body => console.log(body))

相同的功能可以用 ES2017 async 函数: ;(async () => { const response = await fetch('./file.json') const data = await response.json() console.log(data) })()
请求对象请求对象表示请求一个资源请求,它通常通过 new Request() API创建。 例如: const req = new Request('/api/todos')
请求对象提供了几个只读的属性来检查资源请求的细节,包括 method: 请求方法 (GET, POST, 等) url: 请求的URL
headers: 请求的头部信息对象
referrer: 请求的网站来路
cache: 请求的缓存模式(例如:default, reload, no-cache).
并且提供了一些方法,如:json(), text() 和 formData() 来 处理请求体。 全部的API可以查看https://developer.mozilla.org/docs/Web/API/Request 请求头设置 HTTP 请求头是一个基本的功能,fetch通过Headers对象来让我们操作请求头: const headers = new Headers() headers.append('Content-Type', 'application/json')
或者更简单可以这样: const headers = new Headers({ 'Content-Type': 'application/json' })
为了把headers加到请求中,我们用Request对象,把它添加到fetch()函数的参数中,代替传URL参数。 代替下面的代码: fetch('./file.json')
我们这样做 const request = new Request('./file.json', { headers: new Headers({ 'Content-Type': 'application/json' }) }) fetch(request)
Headers 对象没有被限制设置值,我们也可以查询它: headers.has('Content-Type') headers.get('Content-Type')
并且我们可以删除之前设置的header: headers.delete('X-My-Custom-Header')
POST请求Fetch 也可以用其它的 HTTP 方法,如:POST, PUT, DELETE 或者 OPTIONS。 在method属性中指定请求的方法,可以在请求头和请求体中添加额外的参数: 这是一个POST请求的例子: const options = { method: 'post', headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: 'foo=bar&test=1' }
fetch(url, options).catch(err => { console.error('Request failed', err) })
Fetch 弊端虽然fetch比XHR有极大的提高,特别是它在Service Worker中的集成,但是 Fetch 现在还 没有方法中止一个请求 。而且用 Fetch 不能监测上传进度。 如果在你的应用中需要这些功能, Axios 库可以是个不错的选择。 如何取消fetch请求在fetch刚出现的几年,并没有一个方法来取消已经发出的请求。 现在我们可以这样做了,多亏了AbortController 和 AbortSignal,这是个通用的API 来通知 中止 事件。 你可以通过添加一个signal参数来整合这些API: const controller = new AbortController() const signal = controller.signal
fetch('./file.json', { signal })
你可以设置一个超时,在请求发出后5秒后,来取消请求: setTimeout(() => controller.abort(), 5 * 1000)
很方便地,如果fetch已经返回,调用abort()函数不会导致错误。 当取消信号发生,fetch会抛出一个DOMException,异常的name属性值为'AbortError',可以在promise的catch中捕获这个异常: fetch('./file.json', { signal }) .then(response => response.text()) .then(text => console.log(text)) .catch(err => { if (err.name === 'AbortError') { console.error('Fetch aborted') } else { console.error('Another error', err) } })
|