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

如何在重定向前用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:45:36