Request()

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

Request() 构造器创建一个新的Request 对象。

语法

var myRequest = new Request(input[, init]);

参数

input

定义你想要 fetch 的资源。可以是下面两者之一:

  • 一个直接包含你希望 fetch 的资源的 URL 的 USVString
  • 一个 Request 对象。请注意以下行为更新,以在保留安全性的同时使构造函数不太可能引发异常:
    • 如果此对象存在于构造函数调用的另一个起源上,则将除去Request.referrer (en-US)
    • 如果此对象的导航为 Request.mode,则mode将转换为same-origin
init 可选

一个可选对象,包含希望被包括到请求中的各种自定义选项。可用的选项如下:

  • method: 请求的方法,例如:GET, POST
  • headers: 任何你想加到请求中的头,其被放在Headers对象或内部值为ByteString 的对象字面量中。
  • body: 任何你想加到请求中的 body,可以是Blob, BufferSource, FormData, URLSearchParams, USVString,或ReadableStream对象。注意GETHEAD 请求没有 body。
  • mode: 请求的模式,比如 cors, no-cors, same-origin, 或 navigate。默认值为 cors
  • credentials: 想要在请求中使用的 credentials:: omit, same-origin, 或 include。默认值应该为omit。但在 Chrome 中,Chrome 47 之前的版本默认值为 same-origin ,自 Chrome 47 起,默认值为 include
  • cache: 请求中想要使用的 cache mode
  • redirect: 对重定向处理的模式: follow, error, or manual。在 Chrome 中,Chrome 47 之前的版本默认值为 manual,自 Chrome 47 起,默认值为 follow
  • referrer: 一个指定了no-referrer, client, 或一个 URL 的 USVString 。默认值是about:client
  • integrity: 包括请求的 subresource integrity 值 (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).

Errors

Type Description
TypeError Firefox 43 (en-US)后,若 URL 有 credentials,Request() 会抛出 TypeError , 例如 http://user:password\@example.com

Example

在我们的获取请求示例 Fetch Request example (see Fetch Request live) 中,我们使用构造函数创建一个新的Request对象,然后使用 GlobalFetch.fetch 发送请求。由于我们正在获取图像,我们在响应上运行 Body.blob (en-US) 以为其提供正确的 MIME 类型,以便对其进行正确处理,然后为其创建一个 Object URL,并将其显示在 <img> 元素中。

js
var myImage = document.querySelector("img");

var myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then(function (response) {
    return response.blob();
  })
  .then(function (response) {
    var objectURL = URL.createObjectURL(response);
    myImage.src = objectURL;
  });

Fetch Request with init example (参见 Fetch Request init live) 我们做了同样的事情,只不过我们在调用fetch() 时,还传递进了一个 init 对象:

js
var myImage = document.querySelector('img');

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg',myInit);

fetch(myRequest).then(function(response) {
  ...
});

注意你也可以把 init 对象作为参数传递到fetch调用中来达到同样的效果。如下:

js
fetch(myRequest,myInit).then(function(response) {
  ...
});

也可以使用在 init 中使用对象字面量作为 headers

js
var myInit = {
  method: "GET",
  headers: {
    "Content-Type": "image/jpeg",
  },
  mode: "cors",
  cache: "default",
};

var myRequest = new Request("flowers.jpg", myInit);

也可以把 Request 对象再作参数传递进 Request() 构造器来创建一个请求的副本(就像调用clone()一样)。

备注: This last usage is probably only useful in ServiceWorkers (en-US).

规范

Specification
Fetch Standard
# ref-for-dom-request①

浏览器兼容性

BCD tables only load in the browser

参见