亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試在 Go 中設置 cookie,出現 CORS 錯誤

嘗試在 Go 中設置 cookie,出現 CORS 錯誤

Go
收到一只叮咚 2022-05-10 17:05:11
我正在嘗試在 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)))



查看完整回答
反對 回復 2022-05-10
  • 1 回答
  • 0 關注
  • 247 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號