自 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 并将其显示在 元素中。
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);
您也可以将 Request 对象传递给 Request() 构造函数,以创建 Request 的副本(这类似于调用 clone() 方法)。