我从 javascript 中设置了一个 cookie,例如:
setCookie("appointment", JSON.stringify({
appointmentDate: selectedDay.date,
appointmentStartMn: appointment.mnRange[0],
appointmentId: appointment.id || 0,
appointmentUserId: appointment.user.id || 0
})
);
设置 cookie 后,我想将用户重定向到预订页面:
window.location.href = "https://localhost:8080/booking/"
setCookie 函数:
function setCookie(cookieName, cookieValue) {
document.cookie = `${cookieName}=${cookieValue};secure;`;
}
我想从我的 go 后端检索那个 cookie,但我不知道该怎么做。我读过这个问题,因为我以前从未使用过 cookie,但答案似乎告诉我除了设置 document.cookie 之外我不需要做太多事情。
在我的浏览器存储中,我可以看到 cookie 确实按预期设置了。
在我的 Go 后端,我想打印 cookie:
r.HandleFunc("/booking/", handler.serveTemplate)
func (handler *templateHandler) serveTemplate(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("appointment")
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(c.Value)
}
}
//output http: named cookie not present
我缺少的具体内容是什么?我想我混淆了 local/http cookie 但如何实现客户端设置 cookie 的读取?
更新(更多信息请参见答案)
它与golang无关。我的:
appointmentDate: selectedDay.date
格式化为2019-01-01和-不是可以发送到后端的有效字符。它适用于我的浏览器,但需要对 URI 进行编码才能传递。
所以这成功了:
`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`
然后开始(为了节省空间没有在这里发现错误):
cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)
慕虎7371278
相关分类