So, I’m creating a reactjs page where I want to consume a Golang Gorilla Mux api. But whenever I call the api this way:
fetch('http://localhost:8080/commands/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'credentials': 'same-origin'
},
body: JSON.stringify(petitionData),
})
.then(res => res.json())
.then(res => {
console.log("Response: ", res);
})
.catch(error => {
console.error('Error posting petition:', error);
});
I get two errors in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/commands/. (Reason: CORS preflight response did not succeed). Status code: 405.
and Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/commands/. (Reason: CORS request did not succeed). Status code: (null).
.
I already went back and fourth with a lot of code in my API. This is how it is now:
func main() {
r := mux.NewRouter()
r.Use(enableCORS)
r.PathPrefix("/getPics/").Handler(http.StripPrefix("/getPics/", http.FileServer(http.Dir("./images"))))
r.HandleFunc("/", GetUserHandler).Methods("GET")
r.HandleFunc("/commands/", postCommands).Methods("POST")
log.Println("Server listening on port 8080...")
http.ListenAndServe(":8080", r)
}
func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
next.ServeHTTP(w, r)
})
}
Got any ideas about what am I doing wrong?
I tried also calling a function where I passed the pointer enableCors(&w)
to a function and adding all the modifications in this way:
func enableCors(w *http.ResponseWriter) {
header := (*w).Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
}
pls help