尝试在 Go 中设置 cookie,出现 CORS 错误,指出 Access-Control-Allow-Credentials 未设置为 true

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。您知道可能是什么问题吗?

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 代码片段

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