Skip to content Skip to sidebar Skip to footer

Get Request Failed With Custom Header

Here is my AngularJS code, (it works fine if I remove the header option). $http.get(env.apiURL()+'/banks', { headers: { 'Authorization': 'Bearer '+localStorageService.g

Solution 1:

OK, the issue because I fotgot to handle the "OPTIONS" request (to make a CORS browser will send a preflight OPTIONS request first and then the 'real' request if accepted by the server).
I only need to modify my Go server (see the comment):

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/banks", RetrieveAllBank).Methods("GET")
    http.ListenAndServe(":8080", &MyServer{r})
}

type MyServer struct {
    r *mux.Router
}

func (s *IMoneyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin == "http://localhost:8081" {
        rw.Header().Set("Access-Control-Allow-Origin", origin)
        rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        rw.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}

Post a Comment for "Get Request Failed With Custom Header"