4

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? What kind of code should I write and where to put it on Beego?

David Buck
  • 3,752
  • 35
  • 31
  • 35
under5hell
  • 997
  • 3
  • 16
  • 40

2 Answers2

9

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.

Will Krause
  • 626
  • 6
  • 12
  • But, there's another issue. Everytime i send POST request, beego treat it as OPTIONS request. Also it say "http: multiple response.WriteHeader calls". i really have no idea what is goin on. I have set AllowMethods to GET,POST,PUT,PATCH,DELETE.. but still no luck. – under5hell Feb 05 '15 at 06:06
  • here's my question about the issue [link] http://stackoverflow.com/questions/28337387/post-request-treated-as-options-on-beego-framework [/link] – under5hell Feb 05 '15 at 06:18
0

How to set Access-Control-Allow-Origin in Beego framework.

 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,
    }))
David Buck
  • 3,752
  • 35
  • 31
  • 35