进行网络开发:浏览器无法设置Cookie

时间:2018-09-20 12:53:27

标签: go web

我想在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.Cookie{Name: "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。我对这个问题感到困惑。

1 个答案:

答案 0 :(得分:0)

感谢@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);
});