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.

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面