Let me start by saying I’m still very new to programming so please bear with me.

I am trying to create a cookie in my client (localhost:3000) from an API made in Go (localhost:8080), I think I’ve added most headers in the response needed for CORS and the cookie has samesite=none and secure=true but it is still not being set, I have no idea why the cookie isn’t being set, I’ve been stuck for weeks and I know something really dumb is causing this problem. Below I’ve added a picture of the request and response as shown in the chrome devtools network tab and also code of axios where the request is made and code of go where the request is handled in the API server.

Axios:

let config = {
      headers: {
        withCredentials: true,
      },
    };


    axios
      .post(
        "http://localhost:8080/login",

        {
          User: {
            Username: username,
            Password: password,
          },
        },

        config
      )
      .then(function (response) {
        console.log(response)
        console.log(response.data)
        console.log(response.headers)
        console.log(response.data.cookie)
        if (response.status === 200) {
          console.log("if works")
          
        }
      })
      .catch(function (error) {
        console.log(error);
      });

Go:

//Handles account sign ins
func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Println("login handler")
	//decoder := json.NewDecoder(r.Body)
	//var t models.LoginUserData
	//err := decoder.Decode(&t)
	//if err != nil {
	//	log.Println(err)
	//}
	//middleware.SignIn(t.User.Username, t.User.Password)

	http.SetCookie(w, &http.Cookie{Name: "testCookie", Value: "123", Path: "/", HttpOnly: false, SameSite: http.SameSiteNoneMode, Secure: true})
	header := w.Header()
	header.Set("Access-Control-Allow-Credentials", "true")

	//header.Set("Access-Control-Expose-Headers", "Set-Cookie")
	header.Set("Access-Control-Allow-Headers", "Content-Type, withCredentials")
	header.Set("Access-Control-Allow-Origin", "http://localhost:3000")
	header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.WriteHeader(http.StatusOK)
}

//General options/request headers
func preflightHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("handling options...")

	if r.Header.Get("Access-Control-Request-Method") != "" {
		// Set CORS headers
		header := w.Header()
		header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		header.Set("Access-Control-Allow-Origin", "http://localhost:3000")
		header.Set("Access-Control-Allow-Headers", "Content-Type, *")
		header.Set("Access-Control-Allow-Credentials", "true")
	}

	// Adjust status code to 204
	w.WriteHeader(http.StatusNoContent)
}

Request and Response headers:

r/webdev - Trouble creating a cookie with SPA and API

And then the application tab in chrome to prove no cookie was set:

r/webdev - Trouble creating a cookie with SPA and API



Source link

Write A Comment