异步请求302跨域问题记录

3,321 阅读1分钟

问题

前端发送异步请求 -> 接口返回,状态码302 -> 浏览器向重定向的URL发送请求 -> 出现跨域错误

补充:如果在浏览器地址栏里直接输入接口访问,浏览器会自动进行跳转。

解决

如果使用fetch API,出现上述问题后:

fetch('https://xx.xx.com/test.json')
.then(res => console.log(res))
.catch(err => console.log(err))

默认会走到catch的逻辑,但是存在一个问题:捕获到异常,但是无法确认是否是 302后跨域 问题导致的异常。

对于重定向,当浏览器检查到 headers 中存在 Location,会直接进行跳转,不会告知任何请求发送者(fetch),这时候发送者会以为请求还在处理中。所以此时的 fetch 的 then 和catch 都捕获不到信息。

—— 引用自:segmentfault.com/a/119000004…

配置fetch的redirect

A request has an associated redirect mode, which is "follow", "error", or "manual". Unless stated otherwise, it is "follow".

  • follow: Follow all redirects incurred when fetching a resource.
  • error: Return a network error when a request is met with a redirect.
  • Retrieves an opaque-redirect filtered response when a request is met with a redirect, to allow a service worker to replay the redirect offline. The response is otherwise indistinguishable from a network error, to not violate atomic HTTP redirect handling.

—— 引用自:fetch.spec.whatwg.org/#http-redir…

redirect 默认值为 'follow',经过实践:

  • 如果设置为 'manaul',会执行 then 逻辑;
  • 如果设置为 'error',会执行 catch 逻辑;

但是在302后跨域的情况,依然是无法捕获到状态码302,也无法获得首次请求后Response Headerslocation信息。因此目前只能妥协下,排除掉可识别的异常(500,401,代码逻辑本身异常等等),剩下的未知异常,暂时认为是重定向跨域问题。有其他解决方法的,欢迎交流~

补充

后续待了解,关键词:opaqueredirect