2

I have polymer frontend which interact with goapp server. Everything works fine as long as I do not pass authorization token in header. Here is the code at Polymer side

<iron-ajax
      auto
        url="http://localhost:8080/ephomenotes"
        handle-as="json"
        last-response="{{response}}"
        headers="[[_computeHeader()]]"
        debounce-duration="300"></iron-ajax>

_computeHeader() {
        var token = localStorage.getItem("savedToken");
         var obj = {};
         obj.Authorization = "Bearer " + token;
         return obj;
        //return {"Authorization": "Bearer " + token};
      }

At golang server side

w.Header().Set("Access-Control-Allow-Credentials", "true")
if origin := r.Header.Get("Origin"); origin != "" {
    w.Header().Set("Access-Control-Allow-Origin", origin)
}
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
    return
}

Please note is I remove headers="[[_computeHeader()]]" from polymer code then it works..However with Authorization token it throws following error.

XMLHttpRequest cannot load http://localhost:8080/ephomenotes. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Please help

Dheeraj Sarwaiya
  • 145
  • 1
  • 12

1 Answers1

2

Resolved the issue ..

created new route for options

r.OPTIONS("/ephomenotes", optionsheader)
r.GET("/ephomenotes", env.EPHomePage)

This is the new function.

func optionsheader(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

    w.Header().Set("Access-Control-Allow-Credentials", "true")
    if origin := r.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
    }
    w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    // w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")

}

However I am not sure, why this one worked?

Dheeraj Sarwaiya
  • 145
  • 1
  • 12