登录
首页 >  Golang >  Go问答

在 Go 中设置 cookie时遇到 CORS 错误,提示未设置 Access-Control-Allow-Credentials 为 true

来源:stackoverflow

时间:2024-02-22 13:45:23 307浏览 收藏

golang学习网今天将给大家带来《在 Go 中设置 cookie时遇到 CORS 错误,提示未设置 Access-Control-Allow-Credentials 为 true》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在尝试在 go 中设置 cookie。当我运行代码时,我在浏览器中收到 cors 错误,指出 access-control-allow-credentials 未设置为空且需要为 true。但是,在我的代码中它设置为 true。您知道问题可能是什么吗?

cors 错误

从源“http://127.0.0.1:8080”获取“http://127.0.0.1:8000/signup”的访问已被 cors 策略阻止:对预检请求的响应未通过访问控制检查:响应中“access-control-allow-credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”。

go 代码片段

func signup(w http.responsewriter, r *http.request) {
    w.header().set("content-type", "application/json")
    w.header().set("access-control-allow-credentials", "true")

    if r.method == http.methodoptions {
        return
    }
}
r := mux.newrouter()

    header := handlers.allowedheaders([]string{"x-requested-with", "content-type", "authorization", "access-control-allow-credentials", "access-control-allow-origin"})
    methods := handlers.allowedmethods([]string{"get", "post", "put", "delete", "options"})
    origin := handlers.allowedorigins([]string{"http://127.0.0.1:8080"})

r.handlefunc("/signup", signup).methods("post", "options")

log.fatal(http.listenandserve(":8000", handlers.cors(header, methods, origin)(r)))

客户端js

fetch(`${URL_API}/signup`, {
        method: 'post',
        credentials: 'include',
        headers: {
            "Content-type": "application/json"
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then((data) => console.log(data))
    .catch(function (error) {
        console.log('Request failed', error);
    });

解决方案


sideshowbarker 完全正确,谢谢。我没有将 handlers.allowcredentials() 传递到 handlers.cors 中,这导致了上述错误。

固定代码:

creds := handlers.AllowCredentials()
log.Fatal(http.ListenAndServe(":8000", handlers.CORS(header, methods, origin, creds)(r)))

好了,本文到此结束,带大家了解了《在 Go 中设置 cookie时遇到 CORS 错误,提示未设置 Access-Control-Allow-Credentials 为 true》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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