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① |
瀏覽器相容性
載入中…