登录
首页 >  Golang >  Go问答

前端不会在网络选项卡中设置 Cookie

来源:stackoverflow

时间:2024-03-25 23:00:41 465浏览 收藏

前端代码无法在网络选项卡中设置 Cookie,因为请求与服务器之间存在“同源”策略限制。浏览器会阻止来自不同域或端口的前端脚本访问服务器响应中的 Cookie,即使服务器设置了“Set-Cookie”标头。

问题内容

我在后端使用 go 和 mux,在前端使用简单的 html。 在响应中设置cookie的代码(不完整):

import  "github.com/gorilla/sessions" // this is where sessions come from

var 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"] = token
err = 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 标头的内容:

Set-Cookie: uid=jwt_token; Path=/; Expires=Tue, 20 Jul 2021 08:42:37 GMT; Max-Age=86400; HttpOnly; Secure

未设置 cookie,但在网络选项卡中存在“set-cookie”标头。如果您需要有关我的代码的更多详细信息,请在评论中询问,我将发布指向 pastebin 的链接。

编辑:在找到更好的解决方案之前,我从前端设置 cookie,现在后端正在发送带有数据的 json。考虑到我的“初始设计”有点老套,但它现在有效。


正确答案


我认为这与 samesite cookie 属性有关。检查您的响应头 set-cookie 字段末尾是否有一个黄色三角形,表明出现问题(我正在使用 chrome 开发工具)。如果是这样,您应该使用相同的 domainpost 到服务器。例如;

  • 假设您从 http://127.0.0.1:3000 访问前端,并且您的服务器正在侦听端口 8000,那么对服务器的请求应该如下所示;
fetch("http://127.0.0.1:8000/user/register", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          credentials: 'include',
          body: JSON.stringify(user),
        })

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

今天关于《前端不会在网络选项卡中设置 Cookie》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>