浏览器不保存 cookie

我正在使用 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)

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

请求标头


凤凰求蛊
浏览 142回答 2
2回答

慕村9548890

遇到类似问题并正在使用 Fetch API 的任何其他人,请尝试在您的提取请求中设置“凭据:”包括“”,该请求在响应中期待 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) => { ...

潇潇雨雨

请尝试将您的 cookie 放入标题字段中:“Set-Cookie”。例如。:w.Header().Set("Set-Cookie","cookieName=cookieValue")确保响应头有这个字段,并在你的浏览器开发者工具中检查它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go