0

I'm trying to set a cookie in Go. When I run my code I get a CORS error in the browser stating Access-Control-Allow-Credentials is set to nothing and needs to be true. However, in my code it's set to true. Do you know what the issue might be?

CORS Error

Access to fetch at 'http://127.0.0.1:8000/signup' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Go code snippets

func signup(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Credentials", "true")

    if r.Method == http.MethodOptions {
        return
    }
}
r := mux.NewRouter()

    header := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Origin"})
    methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"})
    origin := handlers.AllowedOrigins([]string{"http://127.0.0.1:8080"})

r.HandleFunc("/signup", signup).Methods("POST", "OPTIONS")

log.Fatal(http.ListenAndServe(":8000", handlers.CORS(header, methods, origin)(r)))

Client side JS

fetch(`${URL_API}/signup`, {
        method: 'post',
        credentials: 'include',
        headers: {
            "Content-type": "application/json"
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then((data) => console.log(data))
    .catch(function (error) {
        console.log('Request failed', error);
    });
Community
  • 1
  • 1
Lewis
  • 9
  • 5
  • `localhost` and `127.0.0.1` are not the same host so it's treating it as a cross-origin request. – Adrian Jan 31 '20 at 21:07
  • @Adrian Sorry both for now are 127.0.0.1 have updated the post. Still getting an error. Thanks! – Lewis Jan 31 '20 at 21:14
  • In the same where you have your `handlers.AllowedOrigins(…)` call, have you tried adding `handlers.AllowCredentials(true)`? https://github.com/rs/cors#parameters – sideshowbarker Jan 31 '20 at 23:22

1 Answers1

0

Sideshowbarker was completely correct, thanks. I hadn't passed handlers.AllowCredentials() into handlers.CORS which resulted in the above error.

Fixed code :

creds := handlers.AllowCredentials()
log.Fatal(http.ListenAndServe(":8000", handlers.CORS(header, methods, origin, creds)(r)))
Lewis
  • 9
  • 5