gpt4 book ai didi

go - 尝试在Go中设置Cookie,但收到一条CORS错误,指出Access-Control-Allow-Credentials未设置为true

转载 作者:行者123 更新时间:2023-12-01 22:25:47 25 4
gpt4 key购买 nike

我正在尝试在Go中设置Cookie。当我运行代码时,在浏览器中收到一个CORS错误,指出Access-Control-Allow-Credentials设置为空,并且必须为true。但是,在我的代码中将其设置为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'.转到代码段

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 - 尝试在Go中设置Cookie,但收到一条CORS错误,指出Access-Control-Allow-Credentials未设置为true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60011191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com