为了账号安全,请及时绑定邮箱和手机立即绑定

即使 Cookie 存在于“网络”选项卡中,也不会在前端中设置

即使 Cookie 存在于“网络”选项卡中,也不会在前端中设置

Go
当年话下 2022-09-12 21:02:46
我正在使用Go和mux作为后端,使用简单的html作为前端。用于在响应中设置 Cookie 的代码(未满):import  "github.com/gorilla/sessions" // this is where sessions come fromvar store = sessions.NewCookieStore([]byte("secret"))store.Options = &sessions.Options{        MaxAge:   3600 * 24,        HttpOnly: true,        Path: "/",        Secure: true,    }session, _ := store.Get(request, "uid")session.Values["uid"] = tokenerr = session.Save(request, writer)if err != nil {    log.Fatalln(err)    return}这就是我获取的方式:fetch("http://localhost:8000/user/register", {          method: "POST",          headers: {            "Content-Type": "application/json",          },          credentials: 'include',          body: JSON.stringify(user),        })另外,我在后端启用了cors:c := cors.New(cors.Options{        AllowedOrigins: []string{"http://127.0.0.1:3000"},        AllowCredentials: true,    })设置的饼干标头的内容:Set-Cookie: uid=jwt_token; Path=/; Expires=Tue, 20 Jul 2021 08:42:37 GMT; Max-Age=86400; HttpOnly; Secure未设置 Cookie,但在网络选项卡中存在“设置-Cookie”标头。如果您需要有关我的代码的更多详细信息,请在评论中询问,我将发布一个指向粘贴链接的链接。编辑:在我找到更好的解决方案之前,我从前端设置cookie,现在后端正在发送带有数据的json。考虑到我的“初始设计”,有点笨拙,但它现在有效。
查看完整描述

1 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

我认为这与饼干属性有关。检查响应的标题字段末尾是否有黄色三角形,表示出现问题(我正在使用chrome开发工具)。如果是这样,则应对服务器使用相同的方法。例如;SameSiteSet-CookiedomainPOST


假设您从 访问前端,并且您的服务器正在侦听端口,那么对服务器的请求应该像;http://127.0.0.1:30008000

fetch("http://127.0.0.1:8000/user/register", {

          method: "POST",

          headers: {

            "Content-Type": "application/json",

          },

          credentials: 'include',

          body: JSON.stringify(user),

        })


发生这种情况是因为 和 被视为不同的主机。有关该属性的更多信息,您可以查看MDN文档。localhost127.0.0.1SameSite


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号