【问题标题】:No 'Access-Control-Allow-Origin' header... Is my Beego server misconfigured?没有“Access-Control-Allow-Origin”标头...我的 Beego 服务器配置错误吗?
【发布时间】:2021-06-16 14:50:51
【问题描述】:

我使用 Beego/Golang 作为我的后端,在尝试从我的域中获取 URL 时遇到No 'Access-Control-Allow-Origin' header 的问题。我在谷歌上搜索并将其放入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,
    }))

【问题讨论】:

    标签: go cors beego


    【解决方案1】:

    您同时设置了AllowCredentialsAllowAllOrigins。对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,
    }))
    

    【讨论】:

    • 你的意思是把AllowAllOrigins: true改成AllowOrigins: []string{"https://mywebsite.io/*"}吗?
    • @VII 是的,我就是这个意思。
    猜你喜欢
    • 2017-09-05
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多