Fetch API学习笔记

2018-02-09  本文已影响0人  EL_PSY_CONGROO

Fetch API学习笔记

Fetch是一个现代的概念, 等同于 XMLHttpRequest。它提供了许多与XMLHttpRequest相同的功能,但被设计成更具可扩展性和高效性。

示例

Fetch API中,最常用的就是fetch()函数。它接收一个URL参数,返回一个promise来处理responseresponse参数带着一个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);
});

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

Headers

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")); // []

Request

Request接口定义了通过HTTP请求资源的request格式。

最简单的 Request 是一个URL,可以通过URLGET一个资源。

var req = new Request("/index.html");
console.log(req.method); // "GET"
console.log(req.url); // "http://example.com/index.html"

URL以外的其他属性的初始值能够通过第二个参数传给Request构造函数。这个参数是一个json

var uploadReq = new Request("/uploadImage", {
  method: "POST",
  headers: {
    "Content-Type": "image/png",
  },
  body: "image data"
});

mode属性用来决定是否允许跨域请求,以及哪些response属性可读。可选的mode属性值为same-originno-cors(默认)以及cors

Response

Response实例通常在fetch()的回调中获得。

Response中最常见的成员:

这篇学习笔记参考这个API很“迷人”——(新的Fetch API)),有的部分没有立即理解,留待实践之后回头补充。

上一篇 下一篇

猜你喜欢

热点阅读