Hi I'm implementing rest apis and for that I want to allow cross origin requests to be served.
What I am currently doing:
Go-server code on AWS:
func (c *UserController) Login(w http.ResponseWriter, r *http.Request, ctx *rack.Context) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
...
...
c.render.Json(w,rsp, http.StatusOK)
return
}
Ajax code on localhost:
<script>
$( document ).ready(function() {
console.log( "ready!" );
$.ajax({
url: 'http://ip:8080/login',
crossDomain: true, //set as a cross domain requests
withCredentials:false,
type: 'post',
success: function (data) {
alert("Data " + data);
},
});
});
I am getting the following error on browser console:
XMLHttpRequest cannot load http://ip:8080/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. The response had HTTP status code 422.
I tried adding preflight options:
func corsRoute(app *app.App) {
allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"
f := func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
w.Header().Set("Access-Control-Expose-Headers", "Authorization")
}
return
}
app.Router.Options("/*p", f, publicRouteConstraint)
}
But it is not working.
What can be done to fix it.
Best Answer
I use
gorilla/mux
package to build Go RESTful API server, and client use JavaScript Request can work,My Go Server runs at
localhost:9091
, and the Server code:I find giving
OPTIONS
here is important, otherwise error will occur:after allow
OPTIONS
it works great. I get the idea from This Article.Besides, MDN CORS doc mention:
Following is the api GetPeopleAPI method, note in the method I give comment //Allow CORS here By * or specific origin, I have another similar answer explaining the concept of CORS Here:
In the client, I use html with javascript on
localhost:9092
, and javascript will send request to server fromlocalhost:9092
and the request can successfully get response
"OKOK"
.You can also check response/request header information by tools like
Fiddler
.