我有一個用 Golang 撰寫的后端 REST API 服務。我在 React 前端使用 axios 來 POST 到 API。即使我認為我已經為前端和后端啟用了 CORS,瀏覽器仍然會拋出這個錯誤:
從源“http://localhost:3000”訪問“http://localhost:8080/winERC20”處的 XMLHttpRequest 已被 CORS 策略阻止:Access-Control 不允許請求標頭欄位 access-control-allow-origin - 預檢回應中的允許標頭。
誰能建議我應該怎么做才能解決這個問題?
main.go
func main() {
fmt.Println("Server is serving at http://localhost:8080/")
// Init the mux router
router := mux.NewRouter()
router.HandleFunc("/", helloHandler)
router.HandleFunc("/matchingABI", api.MatchingContractABI)
router.HandleFunc("/winERC20", api.WinERC20_controller).Methods("POST", "OPTIONS")
log.Fatal(http.ListenAndServe(":8080", router))
}
api.go
func WinERC20_controller(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// Try to decode the request body into the struct. If there is an error,
// respond to the client with the error message and a 400 status code.
var p winERC20_RequestBody
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
...
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Success"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Fatalf("Error happened in JSON marshal. Err: %s", err)
}
w.Write(jsonResp)
}
func enableCors(w *http.ResponseWriter) {
header := (*w).Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
}
前端.js
grantERC20(){
// Transfer ERC20 to the player
let url = 'http://localhost:8080/winERC20'
let config = {
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}
}
let data = {
"PublicAddress" : this.props.account,
"Amount": this.props.score
}
axios.post(url, data, config)
.then(
(response) => {console.log(response)},
(error) => {console.log(error);}
);
}
componentDidMount () {
this.grantERC20()
}
uj5u.com熱心網友回復:
為什么,在您的客戶端代碼中,您要添加一個名為Access-Control-Allow-Origin您的請求的標頭?該標頭是回應標頭,而不是請求標頭。此外,CORS 預檢肯定會失敗,因為您的 CORS 配置不允許這樣的請求標頭:
header.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
Access-Control-Allow-Origin補救措施很簡單:只需從您的請求中洗掉該標頭即可。
此外,您應該考慮依賴一些經過驗證的 CORS 中間件,例如https://github.com/rs/cors,而不是“手動”實施 CORS(這很容易出錯)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450169.html
上一篇:3D等距投影的著色
