【问题标题】:Trying to set a cookie in Go, getting a CORS error stating Access-Control-Allow-Credentials is not set to true尝试在 Go 中设置 cookie,收到 CORS 错误,说明 Access-Control-Allow-Credentials 未设置为 true
【发布时间】:2020-08-25 06:05:58
【问题描述】:

我正在尝试在 Go 中设置一个 cookie。当我运行我的代码时,我在浏览器中收到一个 CORS 错误,说明 Access-Control-Allow-Credentials 设置为空且必须为真。但是,在我的代码中,它设置为 true。你知道可能是什么问题吗?

CORS 错误

Access to fetch at 'http://127.0.0.1:8000/signup' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Go 代码 sn-ps

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);
    });

【问题讨论】:

  • localhost127.0.0.1 不是同一个主机,因此它将其视为跨域请求。
  • @Adrian 抱歉,现在都是 127.0.0.1 已更新帖子。仍然出现错误。谢谢!
  • 在您拨打handlers.AllowedOrigins(…) 的地方,您是否尝试过添加handlers.AllowCredentials(true)github.com/rs/cors#parameters

标签: go cookies cross-domain


【解决方案1】:

Sideshowbarker 完全正确,谢谢。我没有将 handlers.AllowCredentials() 传递给 handlers.CORS 导致上述错误。

固定代码:

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

【讨论】:

    猜你喜欢
    • 2016-03-15
    • 2019-11-20
    • 2021-11-06
    • 2017-03-21
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2016-01-21
    • 2019-04-01
    相关资源
    最近更新 更多