没有'Access-Control-Allow-Origin' header...是不是我的Beego服务器配置有问题?

No 'Access-Control-Allow-Origin' header... Is my Beego server misconfigured?

我正在使用 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,
    }))

您正在设置 AllowCredentialsAllowAllOrigins。对 the source code of Beego's cors package 的随意检查表明,因此,对预检请求的响应包含以下 headers 的组合:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

然而,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.

解决此问题的一种方法是允许不是所有来源,而是仅允许您的前端来源;我在下面使用 https://example.com 作为占位符:

beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
    AllowOrigins: []string{"https://example.com"}, // <---
    // -snip-
    AllowCredentials: true,
}))