api代理提取_提取API

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)

XHR 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:

在我看来, XHR有点过于复杂,不要让我开始理解为什么“ 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 Battery API, the fetch API uses JavaScript Promises to handle results/callbacks:

就像更新的Battery API一样 ,fetch API使用JavaScript Promises处理结果/回调:


// Simple response handling
fetch('https://davidwalsh.name/some/url').then(function(response) {
	
}).catch(function(err) {
	// Error :(
});

// Chaining for more "advanced" handling
fetch('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 instance
var headers = new Headers();

// Add a few headers
headers.append('Content-Type', 'text/plain');
headers.append('X-My-Custom-Header', 'CustomValue');

// Check, get, and set header values
headers.has('Content-Type'); // true
headers.get('Content-Type'); // "text/plain"
headers.set('Content-Type', 'application/json');

// Delete a header
headers.delete('X-My-Custom-Header');

// Add initial values
var 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 :

您可以使用appendhasgetsetdelete方法来修改请求标头。 要使用请求标头,请创建一个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!

让我们看看ResponseRequest作用!

请求 (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 GETPOSTPUTDELETEHEAD

  • url - URL of the request

    url请求的URL

  • headers - associated Headers object

    headers -关联的headers Headers对象

  • referrer - referrer of the request

    referrer -请求的推荐人

  • mode - cors, no-cors, same-origin

    mode corsno-corssame-origin

  • credentials - should cookies go with the request? omit, same-origin

    credentials是否应与请求一起使用? omitsame-origin

  • redirect - follow, error, manual

    redirect followerrormanual

  • integrity - subresource integrity value

    integrity -子资源完整性值

  • cache - cache mode (default, reload, no-cache)

    cache -缓存模式( defaultreloadno-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实例,因为Requestfetch签名可以相同。 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:

fetchthen方法提供了一个Response实例,但您也可以自己手动创建Response对象-使用服务工作者时可能会遇到的另一种情况。 通过Response您可以配置:

  • type - basic, cors

    type - basiccors

  • url

    url

  • useFinalURL - Boolean for if url is the final URL

    useFinalURL如果url是最终URL,则为布尔值

  • status - status code (ex: 200, 404, etc.)

    status -状态代码(例如: 200404等)

  • 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 back
fetch('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) { 
  	// <!DOCTYPE ....
  	console.log(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 Introduction to Fetch.  And if you're looking for a polyfill, check out GitHub's implementation.

这本来是fetch 如需更深入的了解,请访问提取简介 如果您正在寻找一个polyfill,请查看GitHub的实现

翻译自: https://davidwalsh.name/fetch

api代理提取

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值