Request: Request() 构造函数
基线 广泛可用
此功能已经成熟稳定,并且可在许多设备和浏览器版本中使用。自 2017 年 3 月.
报告反馈
语法
Request()
构造函数创建一个新的 Request
对象。new Request(input)
new Request(input, options)
js
参数
-
input
- 定义您要获取的资源。这可以是以下两种情况之一:
- 包含您要获取的资源的 URL 的字符串。该 URL 可能是相对于基 URL 的,基 URL 是窗口上下文中的文档
baseURI
,或者工作者上下文中的WorkerGlobalScope.location
。- 一个
Request
对象,实际上是创建一个副本。请注意以下行为更新,这些更新旨在保持安全性,同时使构造函数不太可能抛出异常 - 如果此对象存在于与构造函数调用不同的来源,则会从
Request.referrer
中去除引用。
- 一个
- 如果此对象具有
Request.mode
为navigate
,则mode
值将转换为same-origin
。 -
options
可选一个
RequestInit
对象,其中包含您要应用于请求的任何自定义设置。Request()
构造函数创建一个新的Request
对象。const oldRequest = new Request( "https://github.com/mdn/content/issues/12959", { headers: { From: "webmaster@example.org" } }, ); oldRequest.headers.get("From"); // "webmaster@example.org" const newRequest = new Request(oldRequest, { headers: { From: "developer@example.org" }, }); newRequest.headers.get("From"); // "developer@example.org"
如果您从现有 Request
构造一个新的 Request
,则在选项参数中为新请求设置的任何选项将替换原始 Request
中设置的任何对应选项。例如
异常 | 类型 |
---|---|
描述 |
TypeError |
示例
自 Firefox 43 起,如果 URL 包含凭据(例如 http://user:password@example.com),则 Request()
会抛出 TypeError。
Request()
构造函数创建一个新的 Request
对象。const myImage = document.querySelector("img");
const myRequest = new Request("flowers.jpg");
fetch(myRequest)
.then((response) => response.blob())
.then((response) => {
const objectURL = URL.createObjectURL(response);
myImage.src = objectURL;
});
在我们的 Fetch 请求示例 中(请参阅 Fetch 请求实际演示),我们使用构造函数创建了一个新的 Request
对象,然后使用 fetch()
调用来获取它。由于我们获取的是图像,因此我们对响应运行 Response.blob
以使其具有正确的 MIME 类型,以便正确处理,然后创建其对象 URL 并将其显示在 <img>
元素中。
Request()
构造函数创建一个新的 Request
对象。const myImage = document.querySelector("img");
const reqHeaders = new Headers();
// A cached response is okay unless it's more than a week old.
reqHeaders.set("Cache-Control", "max-age=604800");
const options = {
headers: reqHeaders,
};
// pass init as an "options" object with our headers
const req = new Request("flowers.jpg", options);
fetch(req).then((response) => {
// ...
});
在我们的 带有 init 的 Fetch 请求示例 中(请参阅 带有 init 的 Fetch 请求实际演示),我们执行了相同的操作,只是我们在调用 fetch()
时传入了一个选项对象。在这种情况下,我们可以设置 Cache-Control
值来指示我们允许使用哪种缓存响应。
Request()
构造函数创建一个新的 Request
对象。fetch(req, options).then((response) => {
// ...
});
请注意,您也可以将 options
传入 fetch
调用来获得相同的效果,例如
Request()
构造函数创建一个新的 Request
对象。const options = {
headers: {
"Cache-Control": "max-age=60480",
},
};
const req = new Request("flowers.jpg", options);
您也可以在 options
中使用对象字面量作为 headers
。
Request()
构造函数创建一个新的 Request
对象。const copy = new Request(req);
规范
注意:这种最后的用法可能只在 ServiceWorkers 中有用。 |
---|
规范 # Fetch 标准 |
浏览器兼容性
ref-for-dom-request①