Response: redirected 属性
注意:此功能在 Web Workers 中可用。
redirected 是 Response 接口的一个只读属性,用于指示响应是否是你发起的请求被重定向后的结果。
值
一个布尔值,如果响应表明你的请求已被重定向,则为 true。
示例
检测重定向
要检查响应是否来自被重定向的请求,只需检查 Response 对象上的此标志即可。在下面的代码中,当 fetch 操作期间发生重定向时,会在一个元素中插入文本消息。但请注意,这不像下文 阻止重定向 中描述的那样,可以立即拒绝意外的重定向。
url 属性返回重定向后的最终 URL。
js
fetch("awesome-picture.jpg")
.then((response) => {
const elem = document.getElementById("warning-message-box");
elem.textContent = response.redirected ? "Unexpected redirect" : "";
// final url obtained after redirects
console.log(response.url);
return response.blob();
})
.then((imageBlob) => {
const imgObjectURL = URL.createObjectURL(imageBlob);
document.getElementById("img-element-id").src = imgObjectURL;
});
阻止重定向
检查 redirected 是阻止重定向的糟糕方法,因为重定向已经发生。相反,你应该在调用 fetch() 的 options 参数中将重定向模式设置为 "error",如下所示:
js
fetch("awesome-picture.jpg", { redirect: "error" })
.then((response) => response.blob())
.then((imageBlob) => {
const imgObjectURL = URL.createObjectURL(imageBlob);
document.getElementById("img-element-id").src = imgObjectURL;
});
规范
| 规范 |
|---|
| Fetch # ref-for-dom-response-redirected① |
浏览器兼容性
加载中…