Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios having CORS issue

I added proxy in package.json and it worked great, but after npm run build the CORS issue has resurfaced again, does anyone know how to deal with CORS issue after npm run build in React.

I have tried to add headers in axios request using various methods. However, I failed to add 'Access-Control-Allow-Origin':'*' in axios request. My code is as follwing:

package.json

  "proxy": {       "*":{ "target" : "http://myurl"}    }  

GetData.js

  axios.defaults.baseURL = 'http://myurl';   axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';   axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';   axios.get(serviceUrl, onSuccess, onFailure)   .then(resp => {          let result = resp.data;         onSuccess(result);   })   .catch(error => {         if(onFailure) {             return onFailure(error);         }   })  } 

Note: It has enabled from server side, it is still not working.Currently, I can't change code from server side, My work is limited to client side only.

like image 795
Kiran Avatar asked Jun 20 '18 13:06

Kiran


People also ask

Has been blocked by CORS Axios?

[Solved] Axios request has been blocked by cors no 'Access-Control-Allow-Origin' header is present on the requested resource. Solution 1: Access-Control-Allow-Origin is a response header - so in order to enable CORS - We need to add this header to the response from server.

How do you fix a CORS error?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.


2 Answers

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

like image 92
Murilo Cruz Avatar answered Oct 05 '22 02:10

Murilo Cruz


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)         }     } } 
like image 36
Thushara Buddhika Avatar answered Oct 05 '22 01:10

Thushara Buddhika