Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 850
under5hell Avatar asked Jan 10 '23 00:01

under5hell


1 Answers

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.

like image 191
Will Krause Avatar answered Jan 22 '23 12:01

Will Krause