1

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)))
}

Grant
  • 431
  • 3
  • 8
  • 2
    In addition to @mkopriva's comment, I would add that you shouldn't implement CORS by "manually" setting headers, as it's too error-prone; instead, you should rely on a proven CORS middleware library, which can abstract the complexity of CORS away from you. [gorilla/handlers](https://github.com/gorilla/handlers) provides a CORS middleware, but I would recommend [a more modern alternative](https://github.com/jub0bs/fcors-examples/blob/main/gorilla-mux/main.go). – jub0bs Mar 12 '23 at 12:33
  • @mkopriva the request fails even without the `{ headers:{"Access-Control-Allow-Origin": "*"}` header in the frontend. will definitely look into that link – Grant Mar 12 '23 at 14:41
  • 1
    @jub0bs great! that package looks really helpful – Grant Mar 12 '23 at 14:42
  • @mkopriva I'm kind of confused on what you mean by that. Without the `{ headers:{"Access-Control-Allow-Origin": "*"}` line, I get the same error message in the console as when it was included – Grant Mar 14 '23 at 02:59
  • @Grant my bad, I misread the error message, I read it as complaining about the presence of the header in the request, but it is complaining about its absence in the response. Ignore me. – mkopriva Mar 14 '23 at 04:43
  • @mkopriva never an issue. we all make mistakes from time to time – Grant Mar 14 '23 at 04:57

0 Answers0