Buffalo框架默认CORS中间件硬编码禁用credentials,启用需替换为rs/cors并设AllowCredentials:true及具体AllowedOrigins;同时须配置OPTIONS路由、session跨域写入及前端credentials: 'include'。

Buffalo 框架默认不支持 Credentials 跨域
Buffalo 默认的 CORS 中间件(github.com/gobuffalo/mw-cors)在启用时会将 Access-Control-Allow-Credentials 设为 false,且不允许显式设为 true —— 这是硬编码行为。如果你的前端发请求时带了 credentials: 'include',而服务端没正确响应该 header,浏览器就会直接拒绝响应,报错类似:No 'Access-Control-Allow-Credentials' header is present on the requested resource。
必须手动替换默认 CORS 中间件
Buffalo 的 middleware.Default 里绑的是老版本 mw-cors,它不支持 AllowCredentials 配置。你需要卸载它,改用更灵活的替代方案:
- 删掉
app.Use(middleware.Default)或其中对cors.New的调用 - 改用原生
net/http的http.HandlerFunc手写中间件,或引入github.com/rs/cors -
rs/cors支持细粒度控制:cors.New(cors.Options{AllowCredentials: true, AllowedOrigins: []string{"http://localhost:3000"}}) - 注意:一旦设了
AllowCredentials: true,AllowedOrigins就不能是"*",必须指定具体 origin,否则浏览器拒绝
Cookie 和 Authorization Header 需同步适配
开启 credentials 后,光加 header 不够,后端和前端要协同处理:
Buffalo框架 1.0.1 版本源码包下载,适合需要错误处理改进、依赖更新、render.Download 注释和 request logger 调整的 v1 项目。
- 后端 session/cookie 必须设置
HttpOnly: false、SameSite: "Lax"或"None"(后者要求Secure: true,即只走 HTTPS) - 前端 fetch 必须显式写
credentials: 'include';Axios 则需配置withCredentials: true - 如果用 JWT 放在
Authorizationheader,确保rs/cors的AllowedHeaders包含"Authorization" - Buffalo 的
context.Session()默认依赖 cookie,所以务必检查 session store 是否允许跨域写入(如使用memstore没问题,但 Redis store 需确认 domain 设置)
预检请求(OPTIONS)容易被 Buffalo 路由忽略
Buffalo 的默认路由不自动响应 OPTIONS 方法,尤其当请求含自定义 header(如 Authorization)时,浏览器会先发预检,而 Buffalo 若没配对应 route,就直接 404 或 405,导致跨域失败。
- 手动加一条全局 OPTIONS 路由:
app.Options("/api/{a:path}", buffalo.WrapHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))) - 或者用
rs/cors—— 它内部自动拦截并响应预检,无需额外 route - 验证方式:用 curl 模拟预检:
curl -I -X OPTIONS -H "Origin: http://localhost:3000" -H "Access-Control-Request-Method: POST" http://localhost:3000/api/login,看是否返回 200 + 正确的 CORS headers
真正卡住人的地方往往不是 CORS 配置本身,而是 AllowCredentials: true 和 AllowedOrigins: ["*"] 的互斥性 —— 很多人改完中间件却忘了把通配符换成具体域名,结果一直 401 或静默失败。

















