如何在重定向前用Fetch捕获响应?Spring JWT登录场景求助
解决Fetch自动跟随重定向无法捕获302响应的问题
Fetch API 默认会自动跟随重定向(redirect选项默认值为'follow'),所以你无法直接捕获302状态的重定向响应。要解决这个问题,只需在Fetch配置中添加redirect: 'manual',就能获取到重定向阶段的响应,再手动处理后续请求。
修改后的代码示例
function sub(url, form) { var option = { method: "POST", headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'id=' + form.id.value + "&password=" + form.password.value, redirect: 'manual' // 关键配置:禁止自动跟随重定向 } fetch(url, option) .then(response => { if (response.status === 302) { const token = response.headers.get('access-token'); // 对应后端返回的access-token响应头 const targetUrl = response.headers.get('location'); if (token && targetUrl) { fetch(targetUrl, { headers: { 'Authentication': token // 按约定设置请求头 } }) .then(targetResponse => { // 按需处理目标地址的响应 console.log(targetResponse); }) .catch(err => console.error('请求目标地址失败:', err)); } } }) .catch(err => console.error('登录请求失败:', err)); }
关键注意事项
- 若涉及跨域,后端必须配置
Access-Control-Expose-Headers: access-token,否则前端无法通过response.headers.get()读取自定义响应头。 - 确保代码中响应头、请求头的名称和后端约定完全一致(比如你提到的
access-token和Authentication)。 - 设置
redirect: 'manual'后,所有重定向逻辑需手动实现,浏览器不会自动跳转。
内容的提问来源于stack exchange,提问作者potato
相关产品推荐
相关产品推荐

