gpt4 book ai didi

javascript - 在js中设置cookie,无法在golang中读取

转载 作者:行者123 更新时间:2023-12-01 22:23:22 25 4
gpt4 key购买 nike

我设置了2个cookie,其中1个来自golang,1个来自js,像这样

Golang

var store = sessions.NewCookieStore([]byte("mysession"))
session, _ := store.Get(request, "mysession")
session.Values["usename"] = username
session.Values["status"] = status
err = session.Save(request, response)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}

js
    var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
json_str = JSON.stringify(json_data).toString();
document.cookie =
'mycode=' + json_str +
'; expires=' + now.toUTCString() +
'; path=/';

我打印请求时显示cookie:

cookies :[MySession的= MTU4ODE0MjQ1NXxEdi1CQkFFQ180SUFBUkFCRUFBQVBmLUNBQUlHYzNSeWFXNW5EQWdBQm5OMFlYUjFjd05wYm5RRUFnQUNCbk4wY21sdVp3d0pBQWQxYzJWdVlXMWxCbk4wY21sdVp3d0ZBQU5oYzJRPXxusqTQsJ68z5ZYx13pDMI1vZWVu0pI_zvWh267DQkRYA ==; mycode = [[“200412133557”,11,“6”]]]引荐来源:[ http://localhost:3000/index]

告诉我2个cookie,但是当我想用golang获取cookie时:
func Keranjang(response http.ResponseWriter, request *http.Request) {
cookie1, err := request.Cookie("mysession")
if err != nil {
fmt.Printf("Cant find cookie mysession ")
} else {
fmt.Printf("mysession found ")
fmt.Println(cookie1)
}

cookie2, err := request.Cookie("mycode")
if err != nil {
fmt.Printf("Cant find cookie mycode ")
} else {
fmt.Printf("mycode found ")
fmt.Println(cookie2)
}

}

输出:

MySession的发现MySession的= MTU4ODE0MjQ1NXxEdi1CQkFFQ180SUFBUkFCRUFBQVBmLUNBQUlHYzNSeWFXNW5EQWdBQm5OMFlYUjFjd05wYm5RRUFnQUNCbk4wY21sdVp3d0pBQWQxYzJWdVlXMWxCbk4wY21sdVp3d0ZBQU5oYzJRPXxusqTQsJ68z5ZYx13pDMI1vZWVu0pI_zvWh267DQkRYA ==
无法找到cookie mycode

为什么找不到第二个Cookie?

我有很多尝试

*** try1: cookie2, err := request.Cookie(" mycode") cookie2, err := request.Cookie("mycode=")和相同结果,我输错了什么吗?

*** try2:与 session 获取
var store = sessions.NewCookieStore([]byte("mycode"))
cookie2, err := store.Get(request, "mycode")

并找到cookie'mycode',输出为map:
&{map [] 0xc000038100 true 0xc000096e80 mycode}
但是 map 中缺少值 [“200412133557”,11,“6”] 吗?

*** try3:我在golang中再创建了一个cookie
c.Name = "kuki"
c.Expires = time.Now().Add(5 * time.Minute)
http.SetCookie(response, c)

我用 fmt.Println(request.Cookies())打印所有cookie
输出:

[MySession的= MTU4ODE0MjQ1NXxEdi1CQkFFQ180SUFBUkFCRUFBQVBmLUNBQUlHYzNSeWFXNW5EQWdBQm5OMFlYUjFjd05wYm5RRUFnQUNCbk4wY21sdVp3d0pBQWQxYzJWdVlXMWxCbk4wY21sdVp3d0ZBQU5oYzJRPXxusqTQsJ68z5ZYx13pDMI1vZWVu0pI_zvWh267DQkRYA == 久喜= ]

js创建的cookie“mycode”仍然不可读,
是否有不同类型的JS和Golang Cookie?

最佳答案

终于我明白了
golang中的HTTP Cookie不支持双引号。
因此,根据建议,我将js cookie值解析为base64 window.btoa(json_str),通过cookie并在golang decoded, _ := base64.StdEncoding.DecodeString(cookie2.Value)中解码

关于javascript - 在js中设置cookie,无法在golang中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com