go - 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。考虑到我的“初始设计”有点 hacky,但它现在有效。
解决方案
我认为这与SameSite
cookie 属性有关。检查您的响应的标题Set-Cookie
字段最后是否有一个黄色三角形,表示出现问题(我正在使用 chrome 开发工具)。如果是这样,您应该对服务器使用相同domain
的方法POST
。例如;
- 假设您从 访问前端
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),
})
这是因为localhost
和127.0.0.1
被视为不同的主机。有关该SameSite
属性的更多信息,您可以查看MDN 文档。
推荐阅读
- r - R 中的商业四舍五入 - 即总是从 0.5 开始四舍五入?
- python - 对内层多索引列进行操作
- java - Scala List to Java 不能转换
- powershell - Powershell如何将除新创建的文件之外的所有内容移动到另一个目录
- json - 可在 json 中使用随机元素进行编码
- python - Python:: 关于使用 matplotlib 在一个窗口中绘制多个图形
- python - 使用 Python 在 Windows 10 中对 Selenium Chrome 窗口进行分组
- python - RuntimeError:CUDA 错误:仅使用 GPU 调用 `cublasSgemm(handle)` 时出现 CUBLAS_STATUS_EXECUTION_FAILED
- flutter - 我如何将卡片水平和垂直居中,即在活动的中心
- symfony - Symfony:security.firewalls.main.form_login.default_target_path 被忽略