Request()
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年3月.
* Some parts of this feature may have varying levels of support.
Request() 构造器创建一个新的Request 对象。
语法
new Request(input)
new Request(input, options)
参数
- input
-
定义你想要 fetch 的资源。可以是下面两者之一:
- 一个直接包含你希望 fetch 的资源的 URL 的
USVString。 - 一个
Request对象。请注意以下行为更新,以在保留安全性的同时使构造函数不太可能引发异常:- 如果此对象存在于构造函数调用的另一个起源上,则将除去
Request.referrer。 - 如果此对象的导航为
Request.mode,则mode将转换为same-origin。
- 如果此对象存在于构造函数调用的另一个起源上,则将除去
- 一个直接包含你希望 fetch 的资源的 URL 的
- init 可选
-
一个可选对象,包含希望被包括到请求中的各种自定义选项。可用的选项如下:
method: 请求的方法,例如:GET,POST。headers: 任何你想加到请求中的头,其被放在Headers对象或内部值为ByteString的对象字面量中。body: 任何你想加到请求中的 body,可以是Blob,BufferSource,FormData,URLSearchParams,USVString,或ReadableStream对象。注意GET和HEAD请求没有 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 moderedirect: 对重定向处理的模式:follow,error, ormanual。在 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后,若 URL 有 credentials,Request() 会抛出 TypeError , 例如 http://user:password\@example.com。 |
Example
在我们的获取请求示例 Fetch Request example (see Fetch Request live) 中,我们使用构造函数创建一个新的Request对象,然后使用 GlobalFetch.fetch 发送请求。由于我们正在获取图像,我们在响应上运行 Body.blob 以为其提供正确的 MIME 类型,以便对其进行正确处理,然后为其创建一个 Object URL,并将其显示在 <img> 元素中。
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 对象:
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调用中来达到同样的效果。如下:
fetch(myRequest,myInit).then(function(response) {
...
});
也可以使用在 init 中使用对象字面量作为 headers。
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.
规范
| Specification |
|---|
| Fetch> # ref-for-dom-request①> |
浏览器兼容性
Loading…