Request

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

Fetch API 的 **Request**接口?用来表示资源请求。

你可以使用 Request.Request() ?构造函数创建一个 Request 对象,但是你可能会遇到一个 Request 对象作为其他 API 的操作被返回,比如一个 service workerFetchEvent.request

构造器

Request.Request()

创建一个新的 Request 对象。

属性

Request.method 只读

包含请求的方法 (GET, POST, 等.)

Request.url 只读

包含这个请求的 URL。

Request.headers 只读

包含请求相关的Headers对象。

Request.context (en-US) 只读 已弃用

包含请求的上下文 (例如:audio, image, iframe, 等)

Request.referrer (en-US) 只读

?包含请求的来源 (例如:client)。

Request.referrerPolicy (en-US) 只读

?包含请求来源的策略 (例如:no-referrer)。

Request.mode 只读

包含请求的模式 (例如: cors, no-cors, same-origin, navigate).

Request.credentials 只读

包含请求的证书 (例如: omit, same-origin).

Request.redirect (en-US) 只读

包含?如何处理重定向模式,它可能是一个followerror或者manual

Request.integrity (en-US) 只读

包含请求的子资源的完整性值 (例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).

Request.cache 只读

包含请求的缓存模式 (例如: default, reload, no-cache).

Request实现了Body, 所以它还具有以下属性可用:

Body.body (en-US) 只读

一个简单 getter 用于曝光一个ReadableStream的主体内容。

Body.bodyUsed (en-US) 只读

存储一个Boolean (en-US)判断主体是否已经被用于一个响应中。

方法

Request.clone()

创建当前 request 的副本。

Request实现 Body, 因此它也有以下方法可用:

Body.arrayBuffer() (en-US)

返回解决一个ArrayBuffer表示的请求主体的 promise.

Body.blob() (en-US)

返回解决一个Blob表示的请求主体的 promise.

Body.formData() (en-US)

返回解决一个FormData表示的请求主体的 promise.

Body.json() (en-US)

返回解决一个JSON表示的请求主体的 promise.

Body.text() (en-US)

返回解决一个USVString(文本) 表示的请求主体的 promise.

注意:这些 Body 功能只能运行一次; 随后的调用将通过空 strings/ ArrayBuffers 解析。

示例

在下面的代码中,我们使用 Request ( ) 构造函数创建了一个新的 request 实例(用来请求同一目录下的图片), 然后返回请求的一些属性。

const myRequest = new Request('http://localhost/flowers.jpg');

const myURL = myRequest.url; // http://localhost/flowers.jpg
const myMethod = myRequest.method; // GET
const myCred = myRequest.credentials; // omit

然后,通过将 Request 对象作为参数传递给GlobalFetch.fetch()调用来获取此请求,例如:

fetch(myRequest)
  .then(response => response.blob())
  .then(blob => {
    myImage.src = URL.createObjectURL(blob);
  });

在下面的代码片段中,我们使用Request()构造函数创建了一个新的 request,其中包含一些初始数据和正文内容,用于需要主体有效载荷的 api 请求:

const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});

const myURL = myRequest.url; // http://localhost/api
const myMethod = myRequest.method; // POST
const myCred = myRequest.credentials; // omit
const bodyUsed = myRequest.bodyUsed;

注意:body 类型只能是一个Blob,BufferSource, FormData, URLSearchParams, USVString 或者ReadableStream类型,因此增加一个 JSON 对象的有效载荷则需要字符串化该对象。

例如,您可以通过将Request对象作为参数传递给GlobalFetch.fetch()调用来获取此 api 请求,并获得响应:

fetch(myRequest)
  .then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error('Something went wrong on api server!');
    }
  })
  .then(response => {
    console.debug(response);
    // ...
  }).catch(error => {
    console.error(error);
  });

规范

Specification
Fetch Standard
# request-class

浏览器兼容性

BCD tables only load in the browser

相关链接