Cross-Origin Golang with Gorilla/Mux

Asked

Viewed 483 times

0

In my application I am using the package gorilla/mux next to the gorilla/handlers to enable/configure the CORS of my application, I currently have an GO and a frontend application in vue, in my application vue at the door 8080 i try to call the api on GO at the door 8081 and even with all the CORS configured continuous receiving error from Cross-origin

func main() {
    router := mux.NewRouter()

    allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With"})
    allowedOrigins := handlers.AllowedOrigins([]string{"*"})
    allowedMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})

    router.HandleFunc("/api/get/{name}", getCard)
    router.HandleFunc("/api/autocomplete/{name}", autoComplete)

    http.ListenAndServe(":8081", handlers.CORS(allowedHeaders, allowedOrigins, allowedMethods)(router))
}

If I access the endpoint localhost:8081/api/autocomplete/random by the browser or even by the terminal with curl information is displayed normally if I try to perform a GET from my front-end application on another port I get error below;

Cross-Origin Request Blocked: The Same Origin Policy disallows Reading the remote Resource at http://localhost:8081/api/autocomplete/Random. (Reason: CORS header Access-Control-Allow-Origin' Missing).

What else I need to set up besides these handlers that I’m already using?

1 answer

1

Just add as Header enabled the Content-Type, the variable allowedHeaders will look like this:

allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.