api代理提取
Interested in learning JavaScript? Get my ebook at jshandbook.com
有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书
Since IE5 was released in 1998, we’ve had the option to make asynchronous network calls in the browser using XMLHttpRequest (XHR).
自IE5于1998年发布以来,我们可以选择使用XMLHttpRequest(XHR)在浏览器中进行异步网络调用。
Quite a few years after this, Gmail and other rich apps made heavy use of it, and made the approach so popular that it had to have a name: AJAX.
在此之后的数年中,Gmail和其他丰富的应用程序大量使用了它,并使该方法如此流行,以至于必须使用一个名称: AJAX 。
Working directly with the XMLHttpRequest has always been a pain, and it was almost always abstracted by some library. In particular, jQuery has its own helper functions built around it:
直接使用XMLHttpRequest一直很麻烦,并且几乎总是被某些库抽象化。 特别是,jQuery围绕它构建了自己的帮助器函数:
jQuery.ajax()
jQuery.ajax()
jQuery.get()
jQuery.get()
jQuery.post()
jQuery.post()
and so on.
等等。
They had a huge impact on making asynchronous calls more accessible. In particular, they focused on older browsers to make sure everything still worked.
它们对使异步调用更易于访问产生了巨大影响。 特别是,他们专注于较旧的浏览器,以确保所有功能仍然有效。
The Fetch API has been standardized as a modern approach to asynchronous network requests and uses Promises as a building block.
Fetch API已被标准化为异步网络请求的现代方法,并使用Promises作为构建块。
Fetch at the time of writing (Sep 2017) has a good support across the major browsers, except IE.
撰写本文时(2017年9月)的抓取在IE之外的所有主要浏览器中都有很好的支持。
The polyfill released by GitHub allows us to use fetch
on any browser.
该填充工具通过GitHub的释放使我们能够利用fetch
的任何浏览器。
使用提取 (Using Fetch)
Starting to use Fetch for GET
requests is very simple:
开始将Fetch用于GET
请求非常简单:
fetch('/file.json')
You’re already using it: fetch is going to make an HTTP request to get the file.json
resource on the same domain.
您已经在使用它:fetch将发出HTTP请求以获取同一域上的file.json
资源。
As you can see, the fetch
function is available in the global window
scope.
如您所见, fetch
功能在全局window
范围内可用。
Now let’s make this a bit more useful, let’s actually see what the content of the file is:
现在,让它变得更加有用,让我们实际看看文件的内容是什么:
fetch('./file.json') .then(response => response.json()).then(data => console.log(data))
Calling fetch()
returns a promise. We can wait for the promise to resolve by passing a handler with the then()
method of the promise.
调用fetch()
返回一个promise。 我们可以通过向处理程序传递promise的then()
方法来等待promise解析。
That handler receives the return value of the fetch
promise, a Response object.
该处理程序接收fetch
承诺的返回值,即Response对象。
We’ll see this object in more detail in the next section.
在下一节中,我们将更详细地介绍该对象。
捕捉错误 (Catching errors)
Since fetch()
returns a promise, we can use the catch
method of the promise to intercept any error occurring during the execution of the request, and the processing is done in the then
callbacks:
由于fetch()
返回一个promise,我们可以使用promise的catch
方法来拦截在执行请求期间发生的任何错误, then
在then
回调中完成处理:
fetch('./file.json').then(response => { //...}.catch(err => console.error(err))
响应对象 (Response Object)
The Response Object returned by a fetch()
call contains all the information about the request and the response of the network request.
由fetch()
调用返回的响应对象包含有关请求和网络请求响应的所有信息。
Accessing the headers
property on the response
object gives you the ability to look into the HTTP headers returned by the request:
访问response
对象上的headers
属性使您能够查看请求返回的HTTP标头:
fetch('./file.json').then(response => { console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date'))})
状态 (status)
This property is an integer number representing the HTTP response status.
此属性是代表HTTP响应状态的整数。
101
,204
,205
, or304
is anull body
status101
,204
,205
,或304
是一个null body
状态200
to299
, inclusive, is anOK
status (success)200
到299
(含)之间为OK
状态(成功)301
,302
,303
,307
, or308
is aredirect
301
,302
,303
,307
,或308
是一个redirect
fetch('./file.json') .then((response) => { console.log(response.status) })
statusText (statusText)
statusText
is a property representing the status message of the response. If the request is successful, the status is OK
.
statusText
是代表响应状态消息的属性。 如果请求成功,则状态为OK
。
fetch('./file.json') .then(response => console.log(response.statusText))
网址 (url)
url
represents the full URL of the property that we fetched.
url
代表我们获取的属性的完整URL。
fetch('./file.json') .then(response => console.log(response.url))
身体内容 (Body content)
A response has a body, accessible using the text()
or json()
methods, which return a promise.
响应具有一个正文,可以使用text()
或json()
方法访问该text()
,并返回一个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))
The same can be written using the ES2017 async functions:
(async () => { const response = await fetch('./file.json') const data = await response.json() console.log(data)})()
请求对象 (Request Object)
The Request object represents a resource request, and it’s usually created using the new Request()
API.
Request对象代表资源请求,通常使用new Request()
API创建。
Example:
例:
const req = new Request('/api/todos')
The Request object offers several read-only properties to inspect the resource request details, including
Request对象提供了几个只读属性来检查资源请求的详细信息,包括
method
: the request’s method (GET, POST, etc.)method
:请求的方法(GET,POST等)url
: the URL of the request.url
:请求的URL。headers
: the associated Headers object of the requestheaders
:请求的关联Headers对象referrer
: the referrer of the requestreferrer
:请求的推荐人cache
: the cache mode of the request (e.g., default, reload, no-cache).cache
:请求的缓存模式(例如,默认,重新加载,无缓存)。
And exposes several methods including json()
, text()
and formData()
to process the body of the request.
并且公开了几种方法,包括json()
, text()
和formData()
来处理请求的正文。
The full API can be found here.
完整的API可以在这里找到。
Being able to set the HTTP request header is essential, and fetch
gives us the ability to do this using the Headers object:
能够设置HTTP请求标头至关重要, fetch
使我们能够使用Headers对象执行此操作:
const headers = new Headers()headers.append('Content-Type', 'application/json')
or, simpler:
或者,更简单:
const headers = new Headers({ 'Content-Type': 'application/json' })
To attach the headers to the request, we use the Request object, and pass it to fetch()
instead of simply passing the URL.
要将标头附加到请求,我们使用Request对象,然后将其传递给fetch()
而不是简单地传递URL。
Instead of:
代替:
fetch('./file.json')
we do
我们的确是
const request = new Request('./file.json', { headers: new Headers({ 'Content-Type': 'application/json' }) })
fetch(request)
The Headers object is not limited to setting values, but we can also query it:
Headers对象不仅限于设置值,我们还可以查询它:
headers.has('Content-Type') headers.get('Content-Type')
and we can delete a header that was previously set:
我们可以删除先前设置的标头:
headers.delete('X-My-Custom-Header')
POST请求 (POST Requests)
Fetch also allows you to use any other HTTP method in your request: POST, PUT, DELETE or OPTIONS.
提取还允许您在请求中使用任何其他HTTP方法:POST,PUT,DELETE或OPTIONS。
Specify the method in the method property of the request, and pass additional parameters in the header and in the request body:
在请求的method属性中指定方法,并在标头和请求正文中传递其他参数:
Example of a POST request:
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) })
如何取消获取请求 (How to cancel a fetch request)
For a few years after fetch
was introduced, there was no way to abort a request once opened.
引入fetch
后的几年,一旦打开请求就无法中止请求。
Now we can, thanks to the introduction of AbortController
and AbortSignal
, a generic API to notify abort events
现在,由于引入了AbortController
和AbortSignal
(用于通知中止事件的通用API),我们可以
You integrate this API by passing a signal as a fetch parameter:
您可以通过传递信号作为访存参数来集成此API:
const controller = new AbortController()const signal = controller.signalfetch(‘./file.json’, { signal })
You can set a timeout that fires an abort event 5 seconds after the fetch request has started, to cancel it:
您可以设置一个超时,以在获取请求开始后5秒钟触发中止事件,以将其取消:
setTimeout(() => controller.abort(), 5 * 1000)
Conveniently, if the fetch already returned, calling abort()
won’t cause any error.
方便的是,如果获取操作已经返回,则调用abort()
不会导致任何错误。
When an abort signal occurs, fetch will reject the promise with a DOMException
named AbortError
:
当发生异常中止信号时,访AbortError
将使用名为AbortError
的DOMException
拒绝诺言:
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) }})
Interested in learning JavaScript? Get my ebook at jshandbook.com
有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书
翻译自: https://www.freecodecamp.org/news/understanding-the-fetch-api-a7d4c08c2a7/
api代理提取