跨域请求携带Cookie完整解决方案(前后端协作版)

前端必须配置

1. Axios全局设置(推荐)

// axios全局配置
axios.defaults.withCredentials = true; 
 
// 或在每个请求中单独设置
axios.get('/api', { withCredentials: true })

注意:无论GET/POST/PUT/DELETE请求都需要设置

2. Fetch API配置

fetch('http://localhost/api', {
  credentials: 'include' // 等效于axios的withCredentials
})

3. Vue/React示例

// Vue3组合式API示例
const submitForm = async () => {
  try {
    const res = await axios.post('/login', formData, {
      withCredentials: true // 关键配置
    });
    // 处理响应...
  } catch (err) {
    console.error('请求失败:', err);
  }
}

后端必须配置

1. CORS中间件配置(示例)

Go语言标准库

    r.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"http://localhost:5173"}, // 允许所有来源(开发环境)
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowHeaders:     []string{"Origin", "Content-Type", "Authorization", "X-Requested-With"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
    }))

Node.js Express示例

app.use(cors({
  origin: 'http://localhost:5173', // 必须明确指定
  credentials: true, // 允许凭据
  exposedHeaders: ['set-cookie'] // 暴露set-cookie头
}))

2. Session/Cookie配置要点

配置项 开发环境值 生产环境值
Secure false true (必须HTTPS)
SameSite Lax None
HttpOnly true true
Domain localhost .yourdomain.com
Path / /
// Go语言具体配置示例1
store.Options = &sessions.Options{
    Path:     "/",
    Domain:   "localhost",
    MaxAge:   86400,
    Secure:   false, // 生产环境改为true
    HttpOnly: true,
    SameSite: http.SameSiteLaxMode, // 生产环境改为None
}

// Go语言具体配置示例2
session := sessions.Default(c)
session.Options(sessions.Options{
    MaxAge:   60,
    Path:     "/",
    Domain:   "localhost",
    Secure:   false,
    HttpOnly: true,
    SameSite: http.SameSiteDefaultMode,
})

完整工作流程验证

  1. 请求阶段
POST /api/login HTTP/1.1
Origin: http://localhost:5173
Cookie: existing_cookie=value (如果存在)
  1. 响应阶段
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Credentials: true
Set-Cookie: session_id=abc123; Path=/; Domain=localhost; HttpOnly
  1. 浏览器行为验证

    • 打开DevTools → Application → Cookies
    • 确认cookie已存储且后续请求自动携带

调试技巧

  1. 强制刷新缓存
Chrome地址栏访问:chrome://settings/siteData
删除localhost的所有cookie和数据
  1. 测试命令
# 快速检查CORS配置
curl -I -X OPTIONS http://localhost/api -H "Origin: http://localhost:5173"
  1. 常用断点

    • 前端:检查axios.interceptors请求/响应拦截器
    • 后端:中间件第一行和session保存前

终极检查清单

  • 前端所有请求都带withCredentials
  • 后端不允许Access-Control-Allow-Origin: *
  • Cookie的Domain包含前端的有效域名
  • 非HTTPS环境下Secure=false
  • 浏览器控制台没有黄色警告三角图标
posted @ 2025-12-30 16:32  shuix1ng  阅读(0)  评论(0)    收藏  举报