chirpstack / chirpstack-rest-api

ChirpStack gRPC API to REST proxy.
MIT License
17 stars 14 forks source link

Fix CORS error #13

Closed flashios09 closed 1 year ago

flashios09 commented 1 year ago

Hi,

Even with the PR https://github.com/chirpstack/chirpstack-rest-api/pull/5, the CORS still not working properly image

I had to update the run function:

func run() error {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    r := mux.NewRouter()
    gatewayHandler, err := getGatewayHandler(ctx)
    if err != nil {
        return err
    }

    r.PathPrefix("/api/").Handler(gatewayHandler)
    r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data, err := ui.FS.ReadFile("index.html")
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        w.Write(data)
    })
    r.PathPrefix("/").Handler(http.FileServer(http.FS(ui.FS)))
    corsObj := handlers.AllowedOrigins([]string{*cors})
    // 1. Add the allowed methods header
    corsMethods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"})
    // 2. Add the allowed headers
    corsHeaders := handlers.AllowedHeaders([]string{"Content-Type", "Authorization"})

        // 3. Update the handlers.CORS params
    return http.ListenAndServe(*bind, handlers.CORS(corsObj, corsMethods, corsHeaders)(r))
}

Now it's working: image

I can create a PR :)