使用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
相关产品推荐
相关产品推荐

