duannaiying9662 2015-01-29 13:47
浏览 519
已采纳

如何在beego框架中设置access-control-allow-origin

I'm developing a RESTFul API using beego framework on the server and AngularJS on the client side. Both server and client are in my laptop (still in dev). Client run on 127.0.0.1:8000 and server on 127.0.0.1:8080.

When i try to hit an endpoint (using AngularJS $http service). i get the following error:

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.

I know i have to set this CORS stuff on beego. Unfortunately, after searching google, the only answer i got was from official website (in the comment section) which is not clear enough for me. Any advice guys? what kind of code should i write and where to put it on beego? thanks.

  • 写回答

1条回答 默认 最新

  • dongtangxi1584 2015-02-05 05:42
    关注

    You want to use the cors plugin by including "github.com/astaxie/beego/plugins/cors" in your import statement.

    The package has a commented out example shown below:

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

    So if you want anyone to be able to hit your backend, change the AllowOrigins parameter to just []String{"*"}. And presumably include "GET" in the AllowMethods paramter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题