我有以下代码,用于获取响应标头位置。
let callAuthorize = async() => {
try {
const authorizeResponse = await fetch(requesturl,
{redirect: "manual", mode:'cors',
headers: {
"Cache-Control": "no-store",
"Accept-Charset": "UTF-8",
"Access-Control-Expose-Headers": "location"
}
});
if (authorizeResponse.type === "opaqueredirect") {
window.location.href = authorizeResponse.url;
}
}
catch (e) {
console.log(e)
}
但它重定向到 requesturl,而不是重定向到响应中的标头位置。
由于 CORS 问题,正常的 fetch 调用无法获取响应标头。
您无法直接读取重定向位置。作为解决方法,您可以将浏览器导航到
opaqueredirect
响应(如果您将其存储在缓存中并使用服务工作线程重播响应)。请参阅下面的示例,其中包含一个同源重定向,然后是两个跨源重定向。
index.html
:
<!DOCTYPE html>
<html lang="en">
<head><title>Navigate to opaqueredirect</title></head>
<body>
<button id=button disabled>Navigate to opaqueredirect</button>
</body>
<script>
navigator.serviceWorker.register('sw.js');
navigator.serviceWorker.ready.then(() => {
button.disabled = false;
button.onclick = () => {
fetch('/redirect1', { redirect: 'manual' }).then(
(response) => {
if (response.type === 'opaqueredirect') {
const urlToCache = new URL(response.url);
const uuid = crypto.randomUUID();
urlToCache.searchParams.set('cacheId', uuid);
const requestToCache = new Request(urlToCache);
caches.open('cacheId').then((cache) => {
cache.put(requestToCache, response).then(() => {
window.location.assign(urlToCache);
}).catch(console.error);
}).catch(console.error);
}
},
).catch(console.error);
};
});
</script>
</html>
serve.json
:
{
"redirects": [
{
"source": "/redirect1",
"destination": "/redirect2",
"type": 302
},
{
"source": "/redirect2",
"destination": "https://mock.httpstatus.io/307",
"type": 302
}
]
}
sw.js
:
self.addEventListener('fetch', (event) => {
if (new URL(event.request.url).searchParams.get('cacheId')) {
event.respondWith(caches.open('cacheId').then(async (cache) => {
const cacheMatch = await cache.match(event.request);
if (cacheMatch) {
cache.delete(event.request).then(() => { }).catch(console.error);
return cacheMatch;
}
return fetch(event.request);
}));
}
});
在包含上述文件的目录中运行
npx -y serve
,然后在浏览器中打开localhost:3000
。然后点击按钮,重定向将转到https://mock.httpstatus.io/200
。