浏览器无法保存 cookie。

huangapple go评论86阅读模式
英文:

Browser is not saving cookie

问题

我正在使用React应用程序和Go服务器创建一个应用程序。我在登录请求的响应中使用http.cookie设置cookie,并在网络选项卡中将其发送回。但是浏览器没有保存它。我已经尝试了Chrome和Firefox,但是出了什么问题呢?

// Cors处理程序
r.Use(cors.Handler(cors.Options{
	AllowOriginFunc:  AllowOriginFunc,
	AllowedMethods:   []string{"GET", "POST", "DELETE"},
	AllowedHeaders:   []string{"*"},
	AllowCredentials: true,
}))
func AllowOriginFunc(r *http.Request, origin string) bool {
	if origin == "http://localhost:3000" || origin == "http://127.0.0.1:3000" {
		return true
	}
	return false
}

// 登录路由结束时发送令牌
userDetails := types.User{Name: user.Name, Email: user.Email, Profile_Pic: user.Profile_Pic}
cookie := &http.Cookie{Name: "accessToken", Value: token, MaxAge: int(maxAge), Path: "/api", HttpOnly: true, SameSite: http.SameSiteLaxMode}
http.SetCookie(w, cookie)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userDetails)

编辑:网络选项卡的截图。
响应头

请求头

英文:

I am creating a React app with a Go server. I set the cookie on the login request's response with http.cookie, which sends it back as seen in the network tab. But the browser doesn't save it. Tried with Chrome and Firefox. What am I doing wrong?

// Cors handler
r.Use(cors.Handler(cors.Options{
	AllowOriginFunc:  AllowOriginFunc,
	AllowedMethods:   []string{"GET", "POST", "DELETE"},
	AllowedHeaders:   []string{"*"},
	AllowCredentials: true,
}))
func AllowOriginFunc(r *http.Request, origin string) bool {
	if origin == "http://localhost:3000" || origin == "http://127.0.0.1:3000" {
		return true
	}
	return false
}

// End of Login route sending back the token
	userDetails := types.User{Name: user.Name, Email: user.Email, Profile_Pic: user.Profile_Pic}
	cookie := &http.Cookie{Name: "accessToken", Value: token, MaxAge: int(maxAge), Path: "/api", HttpOnly: true, SameSite: http.SameSiteLaxMode}
	http.SetCookie(w, cookie)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(userDetails)

Edit: Screenshots of the network tab.
Response headers

Request headers

答案1

得分: 11

如果遇到类似问题并且正在使用Fetch API的其他人,请尝试在期望响应中包含Cookie的fetch请求中设置'credentials: "include"。浏览器会将收到的Cookie设置为该请求的Cookie。我错误地认为'credentials'标志必须在接收到Cookie后设置。最终解决了。真不敢相信我花了12个小时来设置一个Cookie。

英文:

Anybody else who comes across a similar problem, and is using the Fetch API, try setting 'credentials: "include"' in your fetch request that is EXPECTING A COOKIE IN THE RESPONSE. The browser then set the cookie it got in the response.

I had the wrong assumption that the 'credentials' flag must be set for requests that occur after the cookie is received. Finally working. Can't believe I spent 12 hours on setting a cookie smh.

fetch(`${url}/login`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
                credentials: "include", // This here
				body: JSON.stringify({
					email: userDetails.email,
					password: userDetails.password,
				}),
			}).then((response) => { ...

答案2

得分: 0

请尝试将你的 cookie 放在头部字段中:"Set-Cookie"。

例如:

w.Header().Set("Set-Cookie", "cookieName=cookieValue")

确保响应头部有这个字段,并在浏览器的开发工具中进行检查。

英文:

please try to put you cookie in header filed:"Set-Cookie".

e.g:

w.Header().Set("Set-Cookie","cookieName=cookieValue")

Make sure the response header has this field, and check it in you browser devtools.

huangapple
  • 本文由 发表于 2022年6月14日 15:00:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/72612730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定