Axios having CORS issue Axios having CORS issue reactjs reactjs

Axios having CORS issue


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


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)        }    }}


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';