我正在嘗試在 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'.去代碼片段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)))客戶端JSfetch(`${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); });
1 回答

大話西游666
TA貢獻1817條經驗 獲得超14個贊
Sideshowbarker 完全正確,謝謝。我沒有將 handlers.AllowCredentials() 傳遞到 handlers.CORS 中,這導致了上述錯誤。
固定代碼:
creds := handlers.AllowCredentials()
log.Fatal(http.ListenAndServe(":8000", handlers.CORS(header, methods, origin, creds)(r)))
- 1 回答
- 0 關注
- 247 瀏覽
添加回答
舉報
0/150
提交
取消