gin.setCookie doesn't work with react.js

Hello !
I’m developing my own technical blog with Go and React.
In login page for admin features like writing or deleting, I wanted to check user’s(my) password and set a cookie if users is authorized.
this API’s
param : input password
LoginData{} : has two fields ‘Id’,‘Password’
But the cookie doesn’t work.
response from Go to React is sent well I think, because when I log-in in admin page, React alerts the id and password are right or wrong at console.
but the cookie doesn’t be set on browser.
I attached codes of Go and React below.

  • go code
eg.POST("/login/:param", func (c *gin.Context){
		param := c.Param("param")
		data := LoginData{}
		if param == "pw" {
			err = c.ShouldBindJSON(&data)
			if err != nil {
				fmt.Println("LOGIN DATA BINDING ERROR")
			}
		}
		fmt.Println(data.Id)
		fmt.Println(data.Password)
		if data.Id != "myid"{
			c.Writer.WriteHeader(http.StatusUnauthorized)
		} else {
			r, err := db.Query(`SELECT pw FROM login where id = "myid"`)
			if err != nil {
				fmt.Println("ID/PW DB INSERT ERROR")
			}
			var pwdata string
			for r.Next() {
				r.Scan(&pwdata)
			}
			err = bcrypt.CompareHashAndPassword([]byte(pwdata), []byte(data.Password))
			if err != nil {
				c.Writer.WriteHeader(http.StatusUnauthorized)
			} else {
				c.SetCookie("admin", "authorized",60*60,"/","",false,false)
			}
		}
	})
  • react code
  const loginHandler = () => {
    const logindata = { id: id, pw: pw };
    console.log(logindata);
    axios
      .post("http://localhost:8080/login/pw", logindata)
      .then((response) => {
        alert("You are logged in.");
                console.log(response.headers["set-cookie"]);
        setCookie(cookies.admin);
      })
      .catch((error) => {
        alert("ID or PW doesn't match.");
      });
  };

the alerts “You are logged in” and “ID or PW doesn’t match” works well.

is there anyone knows about this problem’s solution?

Try setting the hostname to "localhost":

Change:

c.SetCookie("admin", "authorized",60*60,"/","",false,false)

to:

c.SetCookie("admin", "authorized",60*60,"/","localhost",false,false)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.