Cookie在前端没有设置,即使在网络选项卡中存在。

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

Cookie is not being set in the frontend even if it is present in the network tab

问题

我正在使用Go和mux作为后端,使用简单的HTML作为前端。
设置响应中的cookie的代码(不完整)如下:

import "github.com/gorilla/sessions" // 这是sessions的来源

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,
})

设置cookie头的内容如下:

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

尽管在网络选项卡中显示了"set-cookie"头,但cookie并未设置。如果您需要有关我的代码的更多详细信息,请在评论中提问,我将在pastebin上发布链接。

编辑:在找到更好的解决方案之前,我从前端设置cookie,现在后端发送带有数据的JSON。考虑到我的"初始设计",这有点繁琐,但现在可以工作了。

英文:

I'm using Go and mux for the backend and simple html for the frontend.
The code for setting a cookie in the response (not full):

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
}

and this is how I fetch:

fetch("http://localhost:8000/user/register", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          credentials: 'include',
          body: JSON.stringify(user),
        })

Also I have cors enabled on the backend:

c := cors.New(cors.Options{
		AllowedOrigins: []string{"http://127.0.0.1:3000"},
		AllowCredentials: true,
	})

The content of the set-cookie header:

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

The cookie is not being set, but in the network tab the 'set-cookie' header is present. If you need more details about my code, ask in the comments and I will post a link to a pastebin.

Edit: until I find a better solution, I'm setting the cookie from the frontend, now the backend is sending a json with the data. A bit hacky considering my "initial design" but it works for now.

答案1

得分: 4

我认为这与SameSite cookie属性有关。请检查你的响应头中Set-Cookie字段的末尾是否有一个黄色三角形,表示出现了错误(我正在使用Chrome开发工具)。如果有错误,你应该在POST请求到服务器时使用相同的domain。例如:

  • 假设你从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文档

英文:

I think this has to do with the SameSite cookie attribute. Check if your response's header Set-Cookie field has an yellow triangle in the end, indicating that something went wrong (I'm using chrome dev tools). If it does, you should use the same domain to POST to the server. For example;

  • Say that you access the front-end from the http://127.0.0.1:3000, and your server is listening to the port 8000 then the request to the server should like like;
fetch("http://127.0.0.1:8000/user/register", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          credentials: 'include',
          body: JSON.stringify(user),
        })

This is happenning because localhost and 127.0.0.1 are treated as different hosts.
For more information about the SameSite attribute you could check the MDN docs.

huangapple
  • 本文由 发表于 2021年7月19日 16:25:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68437333.html
匿名

发表评论

匿名网友

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

确定