Axios having CORS issue

May be helpful to someone:

I'm sending data from a react application to a golang server.

Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"), the error was fixed.

React form submit function:

async handleSubmit(e) {
    e.preventDefault();
    
    const headers = {
        'Content-Type': 'text/plain'
    };

    await axios.post(
        'http://localhost:3001/login',
        {
            user_name: this.state.user_name,
            password: this.state.password,
        },
        {headers}
        ).then(response => {
            console.log("Success ========>", response);
        })
        .catch(error => {
            console.log("Error ========>", error);
        }
    )
}

Go server got Router,

func main()  {
    router := mux.NewRouter()

    router.HandleFunc("/login", Login.Login).Methods("POST")

    log.Fatal(http.ListenAndServe(":3001", router))
}

Login.go,

func Login(w http.ResponseWriter, r *http.Request)  {

    var user = Models.User{}
    data, err := ioutil.ReadAll(r.Body)

    if err == nil {
        err := json.Unmarshal(data, &user)
        if err == nil {
            user = Postgres.GetUser(user.UserName, user.Password)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            json.NewEncoder(w).Encode(user)
        }
    }
}

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms


Just noting my solution for someone who might get here from googling. I resolved my CORS issue (when calling an external api from my UI in the browser) by setting withCredentials to false in my axios call:

axios({
    method: 'get',
    url: `https://api.someurl.com/subject/v2/resource/somevalue`,
    withCredentials: false,
    params: {
      access_token: SECRET_TOKEN,
    },
  });

In this case, the external api's endpoint's security is based on the access_token.


I have encountered with same issue. When I changed content type it has solved. I'm not sure this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';