api代理提取
One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest
, wasn't really made for what we've been using it for. We've done well to create elegant APIs around XHR but we know we can do better. Our effort to do better is the fetch
API. Let's have a basic look at the new window.fetch
method, available now in Firefox and Chrome Canary.
关于Web上AJAX的最糟糕的秘密之一是,它的底层API XMLHttpRequest
并不是真正针对我们一直在使用的API。 我们已经很好地围绕XHR创建了优雅的API,但是我们知道我们可以做得更好。 我们努力做得更好的是fetch
API。 让我们看一下新的window.fetch
方法,该方法现在在Firefox和Chrome Canary中可用。
XMLHttpRequest (XMLHttpRequest)
is a bit overcomplicated in my opinion, and don't get me started on why "XML" is uppercase but "Http" is camel-cased. Anyways, this is how you use XHR now:
在我看来, 有点过于复杂,不要让我开始理解为什么“ XML”为大写字母,而“ Http”为驼峰式字母。 无论如何,这就是您现在使用XHR的方式:
// Just getting XHR is a mess!if (window.XMLHttpRequest) { // Mozilla, Safari, ... request = new XMLHttpRequest();} else if (window.ActiveXObject) { // IE try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} }}// Open, send.request.open('GET', 'https://davidwalsh.name/ajax-endpoint', true);request.send(null);
Of course our JavaScript frameworks make XHR more pleasant to work with, but what you see above is a simple example of the XHR mess.
当然,我们JavaScript框架使XHR的使用更加愉快,但是您在上面看到的只是XHR混乱的一个简单示例。
基本fetch
用法 (Basic fetch
Usage)
A fetch
function is now provided in the global window
scope, with the first argument being the URL:
现在,在全局window
范围内提供了一个fetch
函数,第一个参数是URL:
// url (required), options (optional)fetch('https://davidwalsh.name/some/url', { method: 'get'}).then(function(response) { }).catch(function(err) { // Error :(});
Much like the updated , the fetch API uses to handle results/callbacks:
就像更新的 ,fetch API使用处理结果/回调:
// Simple response handlingfetch('https://davidwalsh.name/some/url').then(function(response) { }).catch(function(err) { // Error :(});// Chaining for more "advanced" handlingfetch('https://davidwalsh.name/some/url').then(function(response) { return //...}).then(function(returnedValue) { // ...}).catch(function(err) { // Error :(});
If you aren't used to then
yet, get used to it -- it will soon be everywhere.
如果您还不习惯, then
快点习惯吧-它很快就会无处不在。
请求标题 (Request Headers)
The ability to set request headers is important in request flexibility. You can work with request headers by executing new Headers()
:
设置请求标头的能力对于请求灵活性很重要。 您可以通过执行new Headers()
来处理请求标头:
// Create an empty Headers instancevar headers = new Headers();// Add a few headersheaders.append('Content-Type', 'text/plain');headers.append('X-My-Custom-Header', 'CustomValue');// Check, get, and set header valuesheaders.has('Content-Type'); // trueheaders.get('Content-Type'); // "text/plain"headers.set('Content-Type', 'application/json');// Delete a headerheaders.delete('X-My-Custom-Header');// Add initial valuesvar headers = new Headers({ 'Content-Type': 'text/plain', 'X-My-Custom-Header': 'CustomValue'});
You can use the append
, has
, get
, set
, and delete
methods to modify request headers. To use request headers, create a Request
instance :
您可以使用append
, has
, get
, set
和delete
方法来修改请求标头。 要使用请求标头,请创建一个Request
实例:
var request = new Request('https://davidwalsh.name/some-url', { headers: new Headers({ 'Content-Type': 'text/plain' })});fetch(request).then(function() { /* handle response */ });
Let's have a look at what Response
and Request
do!
让我们看看Response
和Request
作用!
请求 (Request)
A Request
instance represents the request piece of a fetch
call. By passing fetch
a Request
you can make advanced and customized requests:
Request
实例代表fetch
调用的请求片段。 通过fetch
Request
您可以发出高级和自定义请求:
method
-GET
,POST
,PUT
,DELETE
,HEAD
method
GET
,POST
,PUT
,DELETE
,HEAD
url
- URL of the requesturl
请求的URLheaders
- associatedHeaders
objectheaders
-关联的headers
Headers
对象referrer
- referrer of the requestreferrer
-请求的推荐人mode
-cors
,no-cors
,same-origin
mode
cors
,no-cors
,same-origin
credentials
- should cookies go with the request?omit
,same-origin
credentials
是否应与请求一起使用?omit
,same-origin
redirect
-follow
,error
,manual
redirect
follow
,error
,manual
integrity
- subresource integrity valueintegrity
-子资源完整性值cache
- cache mode (default
,reload
,no-cache
)cache
-缓存模式(default
,reload
,no-cache
)
A sample Request
usage may look like:
示例Request
用法可能如下所示:
var request = new Request('https://davidwalsh.name/users.json', { method: 'POST', mode: 'cors', redirect: 'follow', headers: new Headers({ 'Content-Type': 'text/plain' })});// Now use it!fetch(request).then(function() { /* handle response */ });
Only the first parameter, the URL, is required. Each property becomes read only once the Request
instance has been created. Also important to note that Request
has a clone
method which is important when using fetch
within the Service Worker API -- a Request is a stream and thus must be cloned when passing to another fetch
call.
仅第一个参数,即URL。 创建Request
实例后,每个属性都变为只读。 同样重要的是要注意Request
具有一个clone
方法,该方法在Service Worker API中使用fetch
时很重要-请求是流,因此在传递到另一个fetch
调用时必须被克隆。
The fetch
signature, however, acts like Request
so you could also do:
但是, fetch
签名的作用类似于Request
因此您还可以执行以下操作:
fetch('https://davidwalsh.name/users.json', { method: 'POST', mode: 'cors', redirect: 'follow', headers: new Headers({ 'Content-Type': 'text/plain' })}).then(function() { /* handle response */ });
You'll likely only use Request
instances within Service Workers since the Request
and fetch
signatures can be the same. ServiceWorker post coming soon!
您可能只在Service Worker中使用Request
实例,因为Request
和fetch
签名可以相同。 ServiceWorker帖子即将发布!
响应 (Response)
The fetch
's then
method is provided a Response
instance but you can also manually create Response
objects yourself -- another situation you may encounter when using service workers. With a Response
you can configure:
fetch
的then
方法提供了一个Response
实例,但您也可以自己手动创建Response
对象-使用服务工作者时可能会遇到的另一种情况。 通过Response
您可以配置:
type
-basic
,cors
type
-basic
,cors
url
url
useFinalURL
- Boolean for ifurl
is the final URLuseFinalURL
如果url
是最终URL,则为布尔值status
- status code (ex:200
,404
, etc.)status
-状态代码(例如:200
,404
等)ok
- Boolean for successful response (status in the range 200-299)ok
成功响应的布尔值(状态范围为200-299)statusText
- status code (ex:OK
)statusText
状态码(例如:OK
)headers
- Headers object associated with the response.headers
-与响应关联的headers
头对象。
// Create your own response for service worker testing// new Response(BODY, OPTIONS)var response = new Response('.....', { ok: false, status: 404, url: '/'});// The fetch's `then` gets a Response instance backfetch('https://davidwalsh.name/') .then(function(responseObj) { console.log('status: ', responseObj.status); });
The Response
also provides the following methods:
Response
还提供以下方法:
clone()
- Creates a clone of a Response object.clone()
-创建一个Response对象的副本。error()
- Returns a new Response object associated with a network error.error()
-返回与网络错误关联的新Response对象。redirect()
- Creates a new response with a different URL.redirect()
-使用其他URL创建新的响应。arrayBuffer()
- Returns a promise that resolves with an ArrayBuffer.arrayBuffer()
-返回使用ArrayBuffer解析的承诺。blob()
- Returns a promise that resolves with a Blob.blob()
-返回以Blob解析的promise。formData()
- Returns a promise that resolves with a FormData object.formData()
-返回使用FormData对象解析的承诺。json()
- Returns a promise that resolves with a JSON object.json()
-返回使用JSON对象解析的Promise。text()
- Returns a promise that resolves with a USVString (text).text()
-返回使用USVString(文本)解析的承诺。
处理JSON (Handling JSON)
Let's say you make a request for JSON -- the resulting callback data has a json
method for converting the raw data to a JavaScript object:
假设您请求JSON-生成的回调数据具有将原始数据转换为JavaScript对象的json
方法:
fetch('https://davidwalsh.name/demo/arsenal.json').then(function(response) { // Convert to JSON return response.json();}).then(function(j) { // Yay, `j` is a JavaScript object console.log(j); });
Of course that's a simple JSON.parse(jsonString)
, but the json
method is a handy shortcut.
当然,这是一个简单的JSON.parse(jsonString)
,但是json
方法是一个方便的快捷方式。
处理基本的文本/ HTML响应 (Handling Basic Text/HTML Responses)
JSON isn't always the desired request response format so here's how you can work with an HTML or text response:
JSON并非始终是所需的请求响应格式,因此这是处理HTML或文本响应的方法:
fetch('/next/page') .then(function(response) { return response.text(); }).then(function(text) { //
You can get the response text via chaining the Promise's then
method along with the text()
method.
您可以通过链接Promise的then
方法和text()
方法来获取响应文本。
处理Blob响应 (Handling Blob Responses)
If you want to load an image via fetch, for example, that will be a bit different:
例如,如果要通过获取来加载图像,那将有所不同:
fetch('https://davidwalsh.name/flowers.jpg') .then(function(response) { return response.blob(); }) .then(function(imageBlob) { document.querySelector('img').src = URL.createObjectURL(imageBlob); });
The blob()
method of the Body mixin takes a Response stream and reads it to completion.
Body mixin的blob()
方法获取一个Response流,并将其读取完成。
过帐表格数据 (Posting Form Data)
Another common use case for AJAX is sending form data -- here's how you would use fetch
to post form data:
AJAX的另一个常见用例是发送表单数据-这是使用fetch
来发布表单数据的方式:
fetch('https://davidwalsh.name/submit', { method: 'post', body: new FormData(document.getElementById('comment-form'))});
And if you want to POST JSON to the server:
如果您想将JSON POST到服务器:
fetch('https://davidwalsh.name/submit-json', { method: 'post', body: JSON.stringify({ email: document.getElementById('email').value, answer: document.getElementById('answer').value })});
Very easy, very eye-pleasing as well!
非常容易,也很令人愉快!
不成文的故事 (Unwritten Story)
While fetch
is a nicer API to use, the API current doesn't allow for canceling a request, which makes it a non-starter for many developers.
尽管fetch
是一个更好用的API,但当前的API不允许取消请求,这使得它对于许多开发人员来说都是无法启动的。
The new fetch
API seems much saner and simpler to use than XHR. After all, it was created so that we could do AJAX the right way; fetch
has the advantage of hindsight. I can't wait until fetch
is more broadly supported!
与XHR相比,新的fetch
存API似乎更简洁明了。 毕竟,它的创建是为了使我们能够以正确的方式进行AJAX; fetch
具有事后观察的优势。 我等不及要广泛支持fetch
!
This is meant to be an introduction to fetch
. For a more in depth look, please visit . And if you're looking for a polyfill, check out .
这本来是fetch
。 如需更深入的了解,请访问 。 如果您正在寻找一个polyfill,请查看 。
翻译自:
api代理提取