浏览器不保存cookie

Dan*_*iar 7 cookies go reactjs

我正在使用 Go 服务器创建一个 React 应用程序。我使用 http.cookie 在登录请求的响应上设置 cookie,这会将其发送回来,如网络选项卡中所示。但浏览器不保存它。尝试使用 Chrome 和 Firefox。我究竟做错了什么?

// 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)
Run Code Online (Sandbox Code Playgroud)

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

请求标头

Dan*_*iar 16

如果其他人遇到类似问题并且正在使用 Fetch API,请尝试在您的 fetch 请求中设置“credentials:“include””,该请求在响应中需要 COOKIE。然后浏览器设置在响应中获得的 cookie。

我有一个错误的假设,即必须为收到 cookie 后发生的请求设置“凭据”标志。终于工作了。不敢相信我花了 12 个小时来设置 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) => { ...
Run Code Online (Sandbox Code Playgroud)