英文:
No 'Access-Control-Allow-Origin' header... Is my Beego server misconfigured?
问题
我正在使用Beego/Golang作为我的后端,并且在从我的域中获取URL时遇到了No 'Access-Control-Allow-Origin' header
的问题。我在Google上搜索到了以下代码,并将其放在func main()
中,但仍然无法解决问题,我仍然得到相同的错误。
//(我的代码)FilterUser用于在用户未登录时将其重定向到登录页面
beego.InsertFilter("/*", beego.BeforeExec, FilterUser)
// 这是我在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,
}))
英文:
I am using Beego/Golang as my backend and having an issue with No 'Access-Control-Allow-Origin' header
when trying to fetch a URL from my domain. I searched on Google and put this in func main()
but it still does not work, I still have the same error.
// (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,
}))
答案1
得分: 4
您正在设置AllowCredentials
和AllowAllOrigins
两个选项。对Beego的cors
包的源代码进行初步检查表明,作为结果,对预检请求的响应包含以下组合的头部信息:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
然而,Fetch标准(定义了CORS的工作原理)指示浏览器拒绝这种组合,因为遵守它将非常不安全。请参阅MDN Web Docs关于CORS的相关段落:
> 当响应一个带凭证的请求时,服务器必须在Access-Control-Allow-Origin
头部的值中指定一个来源,而不是指定通配符"*
"。
修复此问题的一种方法是允许特定来源的请求,而不是所有来源。下面是一个示例,我将https://example.com
用作占位符:
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowOrigins: []string{"https://example.com"}, // <---
// -snip-
AllowCredentials: true,
}))
英文:
You're setting both AllowCredentials
and AllowAllOrigins
. A casual examination of the source code of Beego's cors
package indicates that, as a result, responses to preflight requests contain the following combination of headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
However, the Fetch standard (which defines how CORS works) instructs browsers to reject this combination—because honouring it would be very insecure. See this relevant passage of the MDN Web Docs about CORS:
> When responding to a credentialed request, the server must specify an origin in the value of the Access-Control-Allow-Origin
header, instead of specifying the "*
" wildcard.
One way to fix the issue would be to allow, not all origins, but only the origin of your frontend; I used https://example.com
as a placeholder below:
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowOrigins: []string{"https://example.com"}, // <---
// -snip-
AllowCredentials: true,
}))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论