und*_*ell 4 go angularjs beego
我正在使用服务器上的beego框架和客户端上的AngularJS开发RESTFul API.服务器和客户端都在我的笔记本电脑中(仍在开发中).客户端在127.0.0.1:8000上运行,服务器在127.0.0.1:8080上运行.
当我尝试命中一个端点(使用AngularJS $ http服务).我收到以下错误:
XMLHttpRequest cannot load http://127.0.0.1:8080/v1/products/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
我知道我必须在beego上设置这个CORS的东西.不幸的是,在搜索谷歌后,我得到的唯一答案是来自官方网站(在评论部分),这对我来说不够清楚.有什么建议吗?我应该写什么样的代码以及把它放在哪里?谢谢.
小智 9
您想通过在import语句中包含"github.com/astaxie/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()
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您希望任何人能够点击您的后端,请将AllowOrigins参数更改为[] String {"*"}.并且可能在AllowMethods参数中包含"GET".