问题描述
我使用 Beego/Golang 作为后端,但在尝试从我的域中获取 URL 时遇到了 No 'Access-Control-Allow-Origin' header
问题。我在 Google 上搜索并将其放入 func main()
但它仍然不起作用,我仍然遇到相同的错误。
// (my own code) FilterUser is used to redirect users to login
// when they try to access some pages without logging in
beego.InsertFilter("/*",beego.BeforeExec,FilterUser)
// This is what I found on Google
beego.InsertFilter("*",beego.BeforeRouter,cors.Allow(&cors.Options{
AllowAllOrigins: true,AllowMethods: []string{"GET,POST,PUT,DELETE,OPTIONS"},AllowHeaders: []string{"Origin"},ExposeHeaders: []string{"Content-Length"},AllowCredentials: true,}))
解决方法
您正在设置 AllowCredentials
和 AllowAllOrigins
。对 the source code of Beego's cors
package 的随意检查表明,因此,对预检请求的响应包含以下标头组合:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
然而,Fetch standard(定义 CORS 的工作方式)指示浏览器拒绝这种组合——因为接受它非常不安全。见this relevant passage of the MDN Web Docs about CORS:
响应凭据请求时,服务器必须在 Access-Control-Allow-Origin
标头的值中指定来源,而不是指定“*
”通配符。
解决此问题的一种方法是,不是允许所有来源,而只允许前端的来源;我在下面使用了 https://example.com
作为占位符:
beego.InsertFilter("*",beego.BeforeRouter,cors.Allow(&cors.Options{
AllowOrigins: []string{"https://example.com"},// <---
// -snip-
AllowCredentials: true,}))