4

我正在使用服务器上的 Beego 框架和客户端上的 AngularJS 开发一个 RESTFul API。服务器和客户端都在我的笔记本电脑中(仍在开发中)。客户端在 127.0.0.1:8000 上运行,服务器在 127.0.0.1:8080 上运行。

当我尝试访问端点(使用 AngularJS $http 服务)时,我收到以下错误:

XMLHttpRequest 无法加载http://127.0.0.1:8080/v1/products/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“http://127.0.0.1:8000”。

我知道我必须在 beego 上设置这个 CORS 的东西。不幸的是,在谷歌搜索后,我得到的唯一答案是来自官方网站(在评论部分),这对我来说还不够清楚。有什么建议吗?我应该编写什么样的代码以及将其放在 Beego 的什么位置?

4

2 回答 2

9

您想通过在导入语句中包含“github.com/ataxie/beego/plugins/cors”来使用 cors 插件。

该软件包有一个注释掉的示例,如下所示:

 func main() {
 // CORS for https://foo.* origins, allowing:
 // - PUT and PATCH methods
 // - Origin header
// // - Credentials share
 beego.InsertFilter("*", beego.BeforeRouter,cors.Allow(&cors.Options{
 AllowOrigins: []string{"https://*.foo.com"},
 AllowMethods: []string{"PUT", "PATCH"},
 AllowHeaders: []string{"Origin"},
 ExposeHeaders: []string{"Content-Length"},
 AllowCredentials: true,
 }))
 beego.Run()
 }

因此,如果您希望任何人都能够访问您的后端,请将 AllowOrigins 参数更改为 []String{"*"}。并且大概在 AllowMethods 参数中包含“GET”。

于 2015-02-05T05:42:04.273 回答
0

如何在 Beego 框架中设置 Access-Control-Allow-Origin。

 beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
        AllowAllOrigins: true,
        AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
        ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
        AllowCredentials: true,
    }))
于 2021-09-01T05:39:35.813 回答