重定向:fetch 中的“手动”重定向到请求 URL,而不是重定向到响应中的标头位置

问题描述 投票:0回答:1

我有以下代码,用于获取响应标头位置。

 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 调用无法获取响应标头。

javascript reactjs fetch http-redirect http-status-code-302
1个回答
0
投票

您无法直接读取重定向位置。作为解决方法,您可以将浏览器导航到

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

© www.soinside.com 2019 - 2024. All rights reserved.