【问题标题】:CORS issue - React/Axios Frontend and Golang BackendCORS 问题 - React/Axios 前端和 Golang 后端
【发布时间】:2022-06-30 16:21:45
【问题描述】:

我有一个用 Golang 编写的后端 REST API 服务。我在 React 前端使用 axios 来 POST 到 API。即使我认为我已经为前端和后端启用了 CORS,浏览器仍然会抛出这个错误:

从源“http://localhost:3000”访问“http://localhost:8080/winERC20”的 XMLHttpRequest 已被 CORS 策略阻止:请求标头字段 access-control-allow-origin 不允许预检响应中的 Access-Control-Allow-Headers。

谁能建议我应该怎么做才能解决这个问题?

ma​​in.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")
    }

frontend.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()
}

【问题讨论】:

    标签: reactjs go axios cors


    【解决方案1】:

    为什么,在您的客户端代码中,您要在请求中添加一个名为 Access-Control-Allow-Origin 的标头? That headerresponse header,而不是 request header。此外,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(这很容易出错)。

    【讨论】:

      【解决方案2】:

      TL;DR:在 React 前端使用 Fetch 而不是 Axios,并在 package.json 中添加后端 API URL (http://localhost:8080) 为 proxy .

      我遇到了同样的问题,在花了一天的时间尝试了所有可用的解决方案之后,我通过将 Axios 调用替换为 fetch 来解决这个问题。

      在 Frontend.js 中:

       await fetch("http://localhost:8080/winERC20", {
            method: "POST",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            body: new URLSearchParams(data),
          });
      

      在 Package.json 中:

      "proxy":"http://localhost:8080",
      

      【讨论】:

        猜你喜欢
        • 2020-07-10
        • 2020-12-04
        • 2020-08-04
        • 2018-06-12
        • 2021-10-24
        • 2019-01-05
        • 2021-12-21
        • 2020-02-12
        • 2021-12-15
        相关资源
        最近更新 更多