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);
});