Go Web 开发:Brower 无法设置 cookie
Posted
技术标签:
【中文标题】Go Web 开发:Brower 无法设置 cookie【英文标题】:Go web development: Brower can't set cookie 【发布时间】:2019-02-24 19:06:37 【问题描述】:我想在 Go 中设置 cookie:
func rememberMe(w http.ResponseWriter,username string)
expiration := time.Now().AddDate(0,1,0) // cookie will be stored for 1 month
cookie := http.CookieName: "rememberMe",Value: username,Expires: expiration
http.SetCookie(w,&cookie)
fmt.Println("Cookie has been set.")
响应很好,并且有一个 Set-Cookie 归档:
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: *
Content-Length: 10
Content-Type: text/plain; charset=utf-8
Date: Thu, 20 Sep 2018 12:48:20 GMT
Set-Cookie: rememberMe=buddy; Expires=Sat, 20 Oct 2018 12:48:19 GMT
但是当我使用 Chrome 开发者工具检查 cookie 时,没有 cookie。我对这个问题感到困惑。
【问题讨论】:
我刚试了一下,cookie就设置好了。您是否查看了 Application/Storage/Cookies 下的开发者工具? 如果默认路径不够好,别忘了设置路径。浏览器是否会在后续请求中将 cookie 发送回服务器? 我确实检查了 Application/Storage/Cookies 下的 cookie,但什么也没有。@mbuechmann 这是跨域请求吗?如果是这样,不要忘记在客户端启用 withCredentials 并从服务器发送 Access-Control-Allow-Credentials: true: ***.com/questions/14221722/… 不,浏览器没有在后续请求中发送任何 cookie。设置路径的确切含义是什么?我是一名新的网络开发人员,我无法理解这一点。@Volker 【参考方案1】:感谢@Peter。事情是跨域的。我的后端在 locolhost:8088 运行,前端在 localhost:8080 运行。所以我在后端和前端都做了一些配置。这是后端代码:
func SetupResponse(w *http.ResponseWriter, r *http.Request)
(*w).Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
(*w).Header().Set("Access-Control-Allow-Credentials", "true")
我在前端使用 axios:
this.$axios.create( withCredentials: true )
.get("http://localhost:8088/api/")
.then((response) =>
//....
).catch((error) =>
console.log(error);
);
【讨论】:
以上是关于Go Web 开发:Brower 无法设置 cookie的主要内容,如果未能解决你的问题,请参考以下文章