博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
api代理提取_提取API
阅读量:2524 次
发布时间:2019-05-11

本文共 10312 字,大约阅读时间需要 34 分钟。

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 :

您可以使用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 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代理提取

转载地址:http://pxswd.baihongyu.com/

你可能感兴趣的文章
字符串的常用方法
查看>>
Docker: 快速搭建LNMP网站平台
查看>>
web开发之Servlet 二
查看>>
JAVA提高十:ArrayList 深入分析
查看>>
人工智能入门(六):SVM
查看>>
6.用CXF编写基于Spring的WebService
查看>>
Commands in Powershell
查看>>
bzoj2748 [HAOI2012]音量调节 背包
查看>>
【bzoj2301】[HAOI2011]Problem b 莫比乌斯反演
查看>>
STL
查看>>
浅谈SQL Server中的事务日志(三)----在简单恢复模式下日志的角色
查看>>
ArrayList 源码分析
查看>>
文本超出内容区域后用三个省略号代替
查看>>
不高兴的津津
查看>>
(转) exp1-3://一次有趣的XSS漏洞挖掘分析(3)最终篇
查看>>
sampleSize - 从数组中随机获取 n 个元素
查看>>
ImageLoader介绍2
查看>>
1062 Talent and Virtue (25)
查看>>
java代码读取yarn聚合目录日志
查看>>
spring mvc @ResponseStatus 注解 注释返回中文乱码的问题
查看>>