登录
首页 >  Golang >  Go问答

Go Web开发:Brower无法设置cookie

来源:stackoverflow

时间:2024-04-12 22:45:34 422浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Go Web开发:Brower无法设置cookie》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我想在 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。我对这个问题很困惑。


解决方案


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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>