当前端通过 XHR(XMLHttpRequest) 或 Fetch API 发起请求,而后端返回 302 重定向 时,浏览器默认不会自动跟随重定向(尤其是跨域场景)。以下是解决方案:
1. 检查是否跨域
如果前端和后端域名不同,浏览器会因安全策略限制自动跳转。需确保:
- 后端在
302
响应头中配置允许跨域的Access-Control-Allow-Origin
。 - 如果是复杂请求(如带自定义头),需预检(
OPTIONS
)通过。
2. 前端主动处理重定向
方案一:手动提取 Location
跳转
// Fetch API 示例
fetch('/api/redirect-endpoint', {
redirect: 'manual' // 禁止自动跳转,手动处理
})
.then(response => {
if (response.status === 302) {
const redirectUrl = response.headers.get('Location');
window.location.href = redirectUrl; // JS 强制跳转
}
});
方案二:XHR + 监听响应头
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/redirect-endpoint');
xhr.onreadystatechange = function() {
if (xhr.readyState === xhr.DONE && xhr.status === 302) {
const redirectUrl = xhr.getResponseHeader('Location');
window.location.href = redirectUrl;
}
};
xhr.send();
3. CORS 配置补充
确保后端响应头包含:
HTTP/1.1 302 Found
Location: https://target-url.com
Access-Control-Allow-Origin: https://your-frontend.com
Access-Control-Expose-Headers: Location // !关键:允许前端访问 Location 头
4. Fetch API credentials
配置
如果请求需要携带 Cookie,需显式设置:
fetch('/api/redirect-endpoint', {
credentials: 'include' // include cookies
});
5. Debugging Tips
- 查看浏览器开发者工具:检查 Network Tab,确认
302
和Location
header是否返回。 - 测试直接访问后端接口:用 Postman/cURL验证后端是否正确返回重定向。
总结
场景 | 解决方案 |
---|---|
同域请求 | 无需额外配置,浏览器默认跟随重定向 |
跨域请求 | 1.后端暴露 Location 2.前端手动跳转 |
根据实际需求选择方案即可。
内容由零声教学AI助手提供,问题来源于学员提问