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,
}))
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,
}))