当前位置:首页 > Windows程序 > 正文

(转)这个API很“迷人”

2021-03-26 Windows程序

原文:https://hacks.mozilla.org/2015/03/this-api-is-so-fetching

原标题是This API is So Fetching,Fetching也可以表示迷人的意思——译者注

JavaScript 通过XMLHttpRequest(XHR)来执行异步请求,这个方式已经存在了很长一段时间。虽说它很有用,但它不是最佳API。它在设计上不符合职责分离原则,将输入、输出和用事件来跟踪的状态混杂在一个对象里。而且,基于事件的模型与最近JavaScript流行的Promise以及基于生成器的异步编程模型不太搭(事件模型在处理异步上有点过时了——译者注)。

新的 Fetch API打算修正上面提到的那些缺陷。 它向JS中引入和HTTP协议中同样的原语(即Fetch——译者注)。具体而言,它引入一个实用的函数fetch()用来简洁捕捉从网络上检索一个资源的意图。

Fetch 规范的API明确了用户代理获取资源的语义。它结合ServiceWorkers,尝试达到以下优化:

改善离线体验

保持可扩展性

到写这篇文章的时候,Fetch API被Firefox 39(Nightly版)以及Chrome 42(开发版)支持。在github上,有基于低版本浏览器的兼容实现

特性检测

要检查是否支持Fetch API,可以通过检查 Headers, Request, Response 或者 fetch 在 window 或者 worker 作用域中是否存在。

简单的fetching示例

在Fetch API中,最常用的就是fetch()函数。它接收一个URL参数,返回一个promise来处理response。response参数带着一个Response对象。

fetch("/data.json").then(function(res) { // res instanceof Response == true. if (res.ok) { res.json().then(function(data) { console.log(data.entries); }); } else { console.log("Looks like the response wasn‘t perfect, got status", res.status); } }, function(e) { console.log("Fetch failed!", e); });

如果是提交一个POST请求,代码如下:

fetch("http://www.example.org/submit.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "firstName=Nikhil&favColor=blue&password=easytoguess" }).then(function(res) { if (res.ok) { alert("Perfect! Your settings are saved."); } else if (res.status == 401) { alert("Oops! You are not authorized."); } }, function(e) { alert("Error submitting form!"); });

fetch()函数的参数和传给Request()构造函数的参数保持完全一致,,所以你可以直接传任意复杂的request请求给fetch()。

Headers

Fetch引入了3个接口,它们分别是 Headers,Request 以及 Response 。他们直接对应了相应的HTTP概念,但是基于安全考虑,有些区别,例如支持CORS规则以及保证cookies不能被第三方获取。

Headers接口是一个简单的多映射的名-值表

var content = "Hello World"; var reqHeaders = new Headers(); reqHeaders.append("Content-Type", "text/plain" reqHeaders.append("Content-Length", content.length.toString()); reqHeaders.append("X-Custom-Header", "ProcessThisImmediately");

也可以传一个多维数组或者json:

reqHeaders = new Headers({ "Content-Type": "text/plain", "Content-Length": content.length.toString(), "X-Custom-Header": "ProcessThisImmediately", });

Headers的内容可以被检索:

console.log(reqHeaders.has("Content-Type")); // true console.log(reqHeaders.has("Set-Cookie")); // false reqHeaders.set("Content-Type", "text/html"); reqHeaders.append("X-Custom-Header", "AnotherValue"); console.log(reqHeaders.get("Content-Length")); // 11 console.log(reqHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] reqHeaders.delete("X-Custom-Header"); console.log(reqHeaders.getAll("X-Custom-Header")); // []

一些操作不仅仅对ServiceWorkers有用,本身也提供了更方便的操作Headers的API(相对于XMLHttpRequest来说——译者注)。

由于Headers可以在request请求中被发送或者在response请求中被接收,并且规定了哪些参数是可写的,Headers对象有一个特殊的guard属性。这个属性没有暴露给Web,但是它影响到哪些内容可以在Headers对象中被改变。

可能的值如下:

"none": 默认的

"request": 从Request中获得的Headers只读。

"request-no-cors":从不同域的Request中获得的Headers只读。

"response": 从Response获得的Headers只读。

"immutable" 在ServiceWorkers中最常用的,所有的Headers都只读。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67608.html