我知道有很多與 CORS 相關的問題,但我似乎找不到這個問題的答案。
這是我的服務器端 golang 代碼(我們使用的是 github.com/rs/cors go 模塊):我們基本上有一組需要授權標頭的 api 和一些不需要授權標頭的 api(將結帳與結帳視為訪客功能)
allowedOrigins := []string{"http://localhost:3000", "http://localhost:3001"}
//allowedHeaders := []string{"Authorization"}
c := cors.New(cors.Options{AllowedOrigins: allowedOrigins, AllowCredentials: true})
handler := c.Handler(r)
我發現如下:
// if allowcredentials is set to true, then all non auth requests go through but all auth requests return cors error
// if allowedHeaders: authorization is set then all **authenticated and NON authenticated** POST requests fail. GET works fine for both cases.
更具體地說:當我嘗試執行 POST 請求并設定上面的 AllowedHeaders:authorization 選項時,我得到的錯誤是未設定 AllowedOrigins (??.. 我在 PRE-FLIGHT OPTIONS 回應標頭中得到這個)。
如果我評論該行(如您在上面看到的),那么非身份驗證請求會完美通過,并且 AllowedOrigins hader 會在 OPTIONS 請求中發送回。
uj5u.com熱心網友回復:
修復....
https://github.com/rs/cors
有一個不錯的CorsOptions Debug:true。我用它來檢查發生了什么,當我硬編碼允許授權進入我的服務器時,POST請求隨后抱怨,因為我也在發送內容型別(由客戶端(axios)自動發送,我沒有t指定它)..服務器說了很多“我只識別授權標頭”...我添加了Content-Type它現在可以作業了!
allowedHeaders := []string{"Authorization", "Content-Type"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452362.html
