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

使用Axios传递后端Cookie遭遇CORS拦截问题求助

解决Axios传递后端Cookie时的CORS问题

核心问题分析

当开启withCredentials: true时,浏览器对CORS配置有严格要求:后端不能用*作为Access-Control-Allow-Origin的值,必须指定具体前端域名;同时你的后端CORS头配置、Axios请求写法都存在错误,导致请求被拦截。


一、后端CORS配置修复(Go)

你的中间件有多处错误,修改后的代码如下:

func CORS(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // 替换为前端实际域名,比如http://localhost:3000(根据你的前端端口调整)
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
        w.Header().Set("Access-Control-Allow-Credentials", "true")
        // 允许必要的请求头,按需添加自定义头
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
        // 允许实际用到的HTTP方法,包含OPTIONS预请求
        w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")

        if r.Method == "OPTIONS" {
            fmt.Println("OPTIONS request received")
            w.WriteHeader(http.StatusOK)
            // 处理OPTIONS后直接返回,无需执行后续逻辑
            return
        }

        next(w, r)
    }
}

关键修改说明:

  • Access-Control-Allow-Origin:必须设置为前端具体域名,不能用*,否则浏览器会因withCredentials: true拦截请求。
  • Access-Control-Allow-Methods:之前错误填写了Content-Type,这里要填HTTP方法列表(如POST、OPTIONS)。
  • OPTIONS请求处理:处理完预请求后要return,避免执行后续业务逻辑。

二、Axios请求写法修复

你的Axios参数格式错误,withCredentials和headers需放在同一个配置对象中:

const handleSubmit = (event) => {
    event.preventDefault()
    const data = new FormData(event.currentTarget)
    const [email, password] = [data.get('email'), data.get('password')]

    axios.post('http://localhost:8080/login/', {
        email,
        password,
    }, {
        withCredentials: true,
        headers: { 
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then((response) => {
        for(let entry of response.headers.entries()) {
            console.log('header', entry)
        }
        return response // 必须返回response,否则后续then无法获取
    })
    .then((response) => {
        console.log(response)
        this.setCookie() // 若为React组件,建议用箭头函数避免this指向错误
    })
    .catch(function (error) {
        console.log(error)
    })
}

关键修改说明:

  • Axios的post方法参数为url, data, config,需将withCredentials和headers合并到同一个config对象中,之前的写法把两者作为独立参数是错误的。
  • 第一个then要返回response,否则第二个then会拿到undefined。

三、额外检查项

  1. 确保后端设置Cookie时,Domain(如localhost)和Path(如/)属性配置正确,否则浏览器无法存储Cookie。
  2. 清除浏览器缓存,避免旧的CORS配置干扰测试。
  3. 确认前端和后端的端口对应,Access-Control-Allow-Origin必须和前端地址完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:01:10