0

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?

2
  • What port is the angular app running on and what is the react running on? (e.g. localhost:3000) Commented Mar 29, 2021 at 8:36
  • Reactjs localhost:9999 - Angular localhost:4200 - Go API localhost:5000 Commented Mar 29, 2021 at 8:37

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Christian, concerning r := NewRouter(), I just updated the code
Thank you for your answer, I am about to try it.
Christian, sorry but it's not working. I am still having the same CORS issue from the Angular web application
I added AllowedHeaders: []string{"*"} to make it works
This allows any resource to access the api, can you post a screenshot of the request headers on the angular app from within developer tools?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.