Hello I'm trying to access a GET request on a Golang api running on localhost:8000 from a ReactJS web app running on localhost:3000. But whenever I try to do this, I get the following error:
Fetch API cannot load http://localhost:8000/api/v1/systems.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here's a snippet of my Go server code:
func main() {
session, err := mgo.Dial(mongoURI())
if err != nil {
log.Fatal(err)
}
defer session.Close()
systemsC := session.DB("").C("systems")
flag.Parse()
ctx := context.Background()
kami.Context = ctx
kami.Use("/api/", httpauth.SimpleBasicAuth(os.Getenv("BASIC_USERNAME"), os.Getenv("BASIC_PASSWORD")))
...
kami.Get("/api/v1/systems", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
systems := []alpha.System{}
systemsMap := map[string][]alpha.System{}
err := systemsC.Find(nil).All(&systems)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), 404)
}
systemsMap["systems"] = systems
err = json.NewEncoder(w).Encode(&systemsMap)
if err != nil {
http.Error(w, err.Error(), 500)
}
w.Header().Set("Content-Type", "application/json")
})
kami.Serve()
}
Here's the ReactJS code I'm using to make the GET request:
componentDidMount() {
fetch('http://localhost:8000/api/v1/systems')
.then(function(response) {
return response.json()
}).then(function(data) {
this.setState({ data }, () => console.log(this.state));
});
}
The complete URL requires credentials: http://user:password@localhost:8000/api/v1/systems
I've tried adding various headers to my kami.Get function, but keep getting the same error:
w.Header().Set("Access-Control-Allow-Origin", "*") //This header doesn't work when credentials are sent
Also tried these to no avail:
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
Right now I'm trying to use rs/cors, but not sure on how to add it to my code. Do I only need these 3 lines of code:
mux := http.NewServeMux()
handler := cors.Default().Handler(mux)
http.ListenAndServe(":8080", handler)
Not really sure how to mix mux, kami and cors, any help is appreciated, thank you!
EDIT
Maybe a much simpler question would be if anyone knows how to integrate cors with kami. I think this could fix my problem, just can't figure out how to use them together.