Golang Mux路由添加请求凭据时出现CORS错误求助
问题描述
在Golang Mux路由中配置允许请求凭据,本以为简单直接,但在axios拦截器中设置withCredentials: true后出现了CORS错误。我觉得自己配置没问题,是不是漏了什么?
我的路由服务代码:
log.Fatal(http.ListenAndServe(":8080", handlers.CORS( handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "withCredentials"}), handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}), handlers.AllowedOrigins([]string{"*"}), handlers.AllowCredentials() )(loggedRouter)))
设置Cookie的代码:
// 设置会话Cookie http.SetCookie(w, &http.Cookie{ Name: "session_key", Value: staffAdminSession.SessionKey, Expires: time.Now().Add(time.Hour * 24), HttpOnly: true, })
该Cookie可在Postman中正常设置,但无法在Chrome中生效,请求状态显示CORS错误。
解决办法
问题核心是CORS配置存在冲突,调整以下两点即可:
- 禁止使用通配符源:当启用
handlers.AllowCredentials()时,AllowedOrigins不能设为"*",浏览器会拒绝带凭据的通配符跨域请求。必须指定具体的前端域名,比如[]string{"http://localhost:3000"}(根据你的实际前端地址修改)。 - 移除多余的请求头配置:
AllowedHeaders里的"withCredentials"是无效的,它是axios的客户端配置项,并非HTTP请求头,不需要在服务端允许列表中添加。
修改后的CORS配置示例:
log.Fatal(http.ListenAndServe(":8080", handlers.CORS( handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}), handlers.AllowedOrigins([]string{"http://localhost:3000"}), // 替换为实际前端域名 handlers.AllowCredentials() )(loggedRouter)))
额外注意:
- 确保前端axios的
withCredentials已设为true,且请求的地址与服务端允许的源完全匹配(包括协议、域名、端口)。 - Cookie的
HttpOnly属性正常,它仅限制前端JS读取Cookie,不影响浏览器自动携带Cookie发起请求。
内容的提问来源于stack exchange,提问作者LUKER
相关产品推荐
相关产品推荐

