I've been going through this thread and implementing various way to fix this issue, but it doesn't seem to be working. Looking for some help on what I'm doing wrong.
I'm using Go for the back end and React for the front end. I'm getting this error Access to XMLHttpRequest at 'http://localhost:8080/api/deck/1?deckName=CS+2400' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I don't have this error when making get requests, only for a post request. In react, I have this code:
const EditDeckRoute = ({deckNames, deckID}) => {
const url = "http://localhost:8080/api/deck/" + deckID
const [deckInfo, setDeckInfo] = React.useState([])
React.useEffect(() => {
axios.get(url).then((response) => {
setDeckInfo(response.data)
})
}, [url])
function saveCards() {
axios.post(url, deckInfo, { headers:{"Access-Control-Allow-Origin": "*"}, params:{"deckName": deckNames.get(deckID)}})
}
return (
<>
<div className="wrapper">
<div className="header">
<h1>Edit Flashcards</h1>
<button onClick={saveCards} >Save Cards</button>
</div>
</div>
<div id="detail">
<Outlet />
</div>
</>
)
}
this is what I'm using for my server
main.go
package main
import (
"log"
"net/http"
"os"
"github.com/GrantCanty/flashcards/routes"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
w.Header().Add("Access-Control-Allow-Credentials", "true")
w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("content-type", "application/json;charset=UTF-8")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
ctx := routes.NewAppContext()
r := mux.NewRouter()
r.Use(corsMiddleware)
r.HandleFunc("/api/decks", ctx.GetDeckTitles()).Methods("GET")
r.HandleFunc("/api/deck/{id}", ctx.GetDeck()).Methods("GET")
r.HandleFunc("/api/deck/{id}", ctx.AddDeck()).Methods("POST")
r.HandleFunc("/api/deckcount", ctx.GetDeckLength()).Methods("GET")
r.HandleFunc("/api/user", ctx.GetProfileData()).Methods("GET")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
headersO := handlers.AllowedHeaders([]string{"Access-Control-Allow-Origin"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, headersO, methodsOk)(r)))
}