【发布时间】:2021-09-26 22:20:06
【问题描述】:
我在后端使用 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”标头。如果您需要有关我的代码的更多详细信息,请在 cmets 中询问,我将发布指向 pastebin 的链接。
编辑:在找到更好的解决方案之前,我正在从前端设置 cookie,现在后端正在发送带有数据的 json。考虑到我的“初始设计”有点 hacky,但它现在可以工作。
【问题讨论】:
-
您能否编辑您的问题并添加您在“网络”选项卡中看到的
Set-Cookie标头的内容? -
另外,请说明
sessions的来源。在您的代码 sn-p 中包含所有相关信息(导入等)。 -
@jub0bs 我在问题中添加了这两个细节。
标签: go web cookies session-cookies setcookie