You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RTK Query处理302状态码,获取Location响应头遇阻

解决302响应头无法获取的问题

问题出在浏览器默认会自动跟随302重定向,你当前拿到的response已经是重定向后的页面响应,而非返回302的原始登录接口响应,所以看不到对应的Location头。

要解决这个问题,需要在RTK Query的请求配置里禁用自动重定向:

accountLogin: builder.mutation<any, any>({
   query: (body) => ({
      url: `/accounts/login`,
      method: 'POST',
      body,
      // 新增配置:禁用自动重定向
      fetchOptions: { redirect: 'manual' },
      responseHandler: (response) => {
        console.log(response.status); // 此时会打印302
        const location = response.headers.get('Location'); // 获取重定向URL
        console.log(location);
        return response.text();
      },
  }),
}),

加上fetchOptions: { redirect: 'manual' }后,请求不会自动跳转到Location指向的地址,你就能拿到原始的302响应,进而读取Location头信息。

如果你的项目中RTK Query是基于axios而非原生fetch,需改为设置maxRedirects: 0来禁用重定向,但默认场景下原生fetch的配置即可满足需求。

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:00:58