Mael Fosso
Mael Fosso

Reputation: 400

Go Restful API : CORS configuration works with React but not with Angular

I hope you are doing well. Please, I have this RESTFul API build using Go and Gorilla/mux and rs/cors. Here is the router handler with cors set up

func NewRouter() *mux.Router {

    r := mux.NewRouter().StrictSlash(true)
    r.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        w.WriteHeader(http.StatusOK)
        json.NewEncoder(w).Encode("I'm alive")
    })
    r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet, http.MethodOptions)      // list all charts
    r.HandleFunc("/api/analysis/{projectId}", Create).Methods(http.MethodPost, http.MethodOptions)   // create a chart
    r.HandleFunc("/api/analysis/{projectId}", Delete).Methods(http.MethodDelete, http.MethodOptions) // delete a chart

    return r
}

Here is how I'm starting the server

    r := NewRouter()

    r.Use(loggingMiddleware)
    handler := cors.Default().Handler(r)
    log.Fatal(http.ListenAndServe(":5000", handler))

cors is from https://github.com/rs/cors

From an Angular Web application, I'm calling the route http://localhost:5000/api/analysis/6023d34440baf5016e5b74ea but I receive a Cors error: PreflightMissingAllowOriginHeader

From a React.js Web application, I don't receive any error, No errors !! Successful request

I have also tried the CORS configuration from MUX https://github.com/gorilla/mux#handling-cors-requests but it didn't also works.

Please, what am I doing wrong? How can I fix that?

Upvotes: 0

Views: 850

Answers (1)

Christian
Christian

Reputation: 1808

If you are running your angular/react apps via the start command (or however angular is run) you may need to specify the full URL of where these apps are running (e.g. localhost:9999) for the CORS allowed origins header.

Also two other points:

  1. Remove the http.MethodOptions from the Methods part on your routes - whenever an options HTTP method is detected, the CORS handler will handle it. I don't think those endpoints are ever triggered (because the CORS handler should intercept them), but it's misleading to have the http.MethodOptions in there.
  2. Are you creating two routers? First with r:= mux.NewRouter() and then again with r:= NewRouter() - or is this just a mix up from copy/pasting it?

This can be done for rs/cors package as shown below:

r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet)
// ... add other routes here

// Then wrap in the CORS handler
corsHandler := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost", "http://localhost:4200", "HTTP://localhost:9999"},
        AllowedHeaders: []string{"*"},
    }).Handler(r)

// Now serve the API
http.ListenAndServe(":5000", corsHandler)

And if you need cookies:

r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/api/analysis/{projectId}", List).Methods(http.MethodGet)
// ... add other routes here

// Then wrap in the CORS handler
corsHandler := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost", "http://localhost:4200", "HTTP://localhost:9999"},
        AllowedHeaders: []string{"*"},
        AllowCredentials: true,
    }).Handler(r)

// Now serve the API
http.ListenAndServe(":5000", corsHandler)

Upvotes: 1

Related Questions