我正在使用Go和mux作為后端,使用簡單的html作為前端。用于在響應中設置 Cookie 的代碼(未滿):import "github.com/gorilla/sessions" // this is where sessions come fromvar 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"] = tokenerr = 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??紤]到我的“初始設計”,有點笨拙,但它現在有效。
1 回答

蠱毒傳說
TA貢獻1895條經驗 獲得超3個贊
我認為這與餅干屬性有關。檢查響應的標題字段末尾是否有黃色三角形,表示出現問題(我正在使用chrome開發工具)。如果是這樣,則應對服務器使用相同的方法。例如;SameSiteSet-CookiedomainPOST
假設您從 訪問前端,并且您的服務器正在偵聽端口,那么對服務器的請求應該像;http://127.0.0.1:30008000
fetch("http://127.0.0.1:8000/user/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: 'include',
body: JSON.stringify(user),
})
發生這種情況是因為 和 被視為不同的主機。有關該屬性的更多信息,您可以查看MDN文檔。localhost127.0.0.1SameSite
- 1 回答
- 0 關注
- 94 瀏覽
添加回答
舉報
0/150
提交
取消