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

如何在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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀