我正在使用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: uid=jwt_token; Path=/; Expires=Tue, 20 Jul 2021 08:42:37 GMT; Max-Age=86400; HttpOnly; Secure
未设置 Cookie,但在网络选项卡中存在“设置-Cookie”标头。如果您需要有关我的代码的更多详细信息,请在评论中询问,我将发布一个指向粘贴链接的链接。
编辑:在我找到更好的解决方案之前,我从前端设置cookie,现在后端正在发送带有数据的json。考虑到我的“初始设计”,有点笨拙,但它现在有效。
蛊毒传说
相关分类