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

跨子域请求传递HttpOnly Cookie失败?Axios请求返回401排查

问题描述

在mycooldomain.com的HTML页面中,使用axios向login.mycooldomain.com发起登录请求,前端代码如下:

const smartAxiosLogin = axios.create({
    timeout: 5000, // 5 seconds
    baseURL: 'https://login.mycooldomain.com:4000/api',
    withCredentials: true,
});
const smartAxios = axios.create({
    timeout: 5000, // 5 seconds
    baseURL: 'https://smartpmoapi.mycooldomain.com:4100/api',
    withCredentials: true,
});
$("#login_form").submit(function(e) {
    e.preventDefault();
    let email= $('#username_login').val();
    let password= $('#password_login').val();
    smartAxiosLogin.post("/login",{ email:email, password:password })
    .then(function (response) {
        if(response.status==200){
            smartAxios.get("/profile").then(function(response){console.log(response)}).catch(function(error){console.log(error)});
        }
    })
    .catch(function (error) {
        console.log(error);
    }); 
});

登录成功后,accessToken被存储在HttpOnly Cookie中,但向另一个子域smartpmoapi.mycooldomain.com发起/profile请求时,始终无法携带Cookie,返回401(未授权)。

后端设置Cookie的代码如下:

res.cookie('accessToken', token, { maxAge: 3600000, httpOnly: true, secure: true, Domain: '.mycooldomain.com', Path: '/', SameSite: 'None' });

res.cookie('refreshToken', _token, { maxAge: 86400000, httpOnly: true, secure: true, Domain: '.mycooldomain.com', Path: '/', SameSite: 'None' });

同一API端点下请求正常,跨子域请求出现问题,请问问题出在哪里?

问题分析与解决

以下是可能导致跨子域请求无法携带Cookie的原因及对应解决方法:

  • 检查Domain属性的大小写一致性:部分浏览器对Cookie的Domain值大小写敏感,确保后端设置的.mycooldomain.com和实际域名完全一致(全小写),避免因大小写不匹配导致Cookie无法跨子域共享。
  • 配置正确的CORS规则:smartpmoapi.mycooldomain.com的后端必须配置CORS:
    • 明确指定Access-Control-Allow-Origin为前端页面的源(即https://mycooldomain.com,若有端口需带上完整端口号),不能使用*;
    • 必须设置Access-Control-Allow-Credentials: true,允许跨域请求携带Cookie。
  • 确认HTTPS环境:因为Cookie设置了secure: true和SameSite: None,前端页面和两个API域名都必须使用HTTPS协议,否则浏览器会拒绝存储或携带这类Cookie。
  • 验证axios的withCredentials配置:虽然已在axios实例中开启withCredentials: true,但需确认后续请求没有被其他配置覆盖,确保该参数在跨域请求时生效。
  • 检查端口与源的匹配:浏览器将不同端口视为不同源,若前端页面运行在非标准端口(如8080),则CORS的Access-Control-Allow-Origin必须包含完整的https://mycooldomain.com:端口号,否则跨域请求会被拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:46:22