Axios having CORS issue
Asked Answered
H

12

147

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.

Haymow answered 20/6, 2018 at 13:36 Comment(2)
M
132

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

Microcline answered 20/6, 2018 at 13:38 Comment(7)
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.Haymow
maybe it isn't configured correctly on the server side. Check the google chrome's network tab. There should be 2 requests. The first one is a preflight request (just to check CORS headers). Maybe the server isn't answering correctly this first preflight requestMicrocline
Ya, you were right, it needs to be solved from server side.Haymow
For asp.net Core 2 webapi you can follow instructions here at Official Microsoft DocumentationRotor
If you don't have control of the server side, this still needs solving some other way.Pave
Access Control Allow Origin should not be *, it should be a value for an accepted Origin. The suggested best practice is to check the Origin against an allow-list, then return the accepted domain in the response as the value of the header. So says MDN.Anjelicaanjou
I am facing an issue with axios. Although I have enabled CORS on my server, I am unable to hit it from the client. However, when I use the fetch method, everything works fine.Catholic
V
35

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.

Vaduz answered 6/8, 2021 at 19:38 Comment(2)
According to the documentation, the withCredentials should be set to false by default, but glad to know it might work.Trachyte
This solved my CORS issues when making requests to AWS API Gateway endpoints.Enemy
S
18

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';
Shutdown answered 15/2, 2019 at 16:41 Comment(3)
This works because you changed to a simple request in which case the response from your server only needs to include the header Access-Control-Allow-OriginBarely
Actually after that. I realized I have some errors in Access-Control-Allow-Headers which is need to be organized correctly. I think the point is this.Shutdown
I was making a post request from a React FE to PHP BE, and I kept getting the cors Error which was strange because I had set all the CORS stuff on my server. Thanks, dude! I owe you a cup of coffee.Buntline
K
18

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)
        }
    }
}
Kaliope answered 27/12, 2019 at 6:7 Comment(1)
it worked for me as well when I added the "Access-Control-Allow-Origin" to my headers! I know im 2 years late, but how was this able to address the CORS issue? thanks so much!Eben
T
6

I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.

You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security

After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.

Hope this helps!

Thayer answered 7/6, 2020 at 0:36 Comment(2)
this actually helped me solve my problem. ThanksShorthorn
Yes, this is 'bad' practice in a way, but it's good enough to test from the local dev box while coding. Then you deploy to an actual test/staging environment with https where you have proper names and certificates and CORS headers properly in place to do proper/more complete integration testing that simulate the prod environment. Thank you so much for getting me unstuck.Quito
G
6

This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources. So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.

Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.

const cors = require("cors");

app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));

app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));

I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.

Greataunt answered 7/10, 2021 at 10:55 Comment(0)
B
4

This work out for me :

in javascript :

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order
          }).then(function (response) {
            console.log(response.data);
          });

and in the backend (.net core) : in startup:

 #region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

and in controller before action

[EnableCors("AllowOrigin")]
Bluejacket answered 15/6, 2020 at 5:7 Comment(2)
Stop allowing all originsSharynshashlik
This is fine for only local testing, should be very careful while deployingChloras
B
3

I come across this thread when having the same problem using Axios. What was not mentioned in the responses is that using fetch with no-cors mode can solve your issue.

Why ?

Apparently, Axios uses a XMLHttpRequest under the hood, not Request and Axios fails because CORS is still being enforced and no-cors mode is not supported.

Check this thread for more information

Bighorn answered 24/10, 2021 at 21:3 Comment(0)
A
2

CORS issue is something you will only encounter on a browser. It occurs because the server does not allow request from others servers

i.e If I am sending request from http://localhost:3000 to any api(http://example.com/users) to get the user data from here.

If the server does not recognize your local host

@CrossOrigin(Origin = "*") // this will allow any request from any server you will not face CORS issue if you us this annotation

Now what if you are sending a request using axios in react to another sever which is not in your control the way to overcome that issue is by using http-proxy-middleware

npm i http-proxy-middleware // install this dependency

axios.{ method: 'post', url: '/endpoint', headers: { 'Content-Type': 'application/json', }, proxy: createProxyMiddleware({ target: 'https://www.api.com', changeOrigin: true}), data: data };

Now in this way a proxy request to www.api.com/endpoint will be sent and thus you will not receive a CORS issue

also add this in your package.json

"proxy": "https://www.api.com"

Atlantis answered 15/3, 2021 at 16:16 Comment(1)
if you are using your own server just allow cors on the server-side. if you are using some other API ( eg one signal ), you need to create a server for requesting the API endpoints. Most of the API providers block client-side requests to there API.Disuse
A
-3

Please try this .. it worked for me

axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
        console.log("result",result);
      }).catch((error)=>{
        console.log("Error",error);
      });
Anabolite answered 5/4, 2021 at 11:47 Comment(2)
The property 'crossdomain' suggested is not accepted, nor does it work. I confirmed this for version 0.21.1 of axios (newest at this point).Eponymous
Pankaj Solution's work for meAlexia
A
-10

Just simply add this to your headers

headers : {
    'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}

No need to use Access-Control-Allow-Origin : *

Alter answered 18/5, 2021 at 8:28 Comment(0)
P
-17

CORS issue can be simply resolved by following this:

Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"
Preponderance answered 25/7, 2020 at 13:12 Comment(3)
Excelent option, with this browser running I can prove that the error is CORS and the people in the server side have to solve the error. You know, they believe that the error is in my side, no in the server.Jataka
Gadzooks... For anyone wondering about the downvotes here, one should, in cases where the remote server did not set Access-Control-Allow-Origin to *, you should proxy the request through your own server. That is, you should make the request to your own server, and have that perform the request of the remote server on your behalf. That provides safety for all. Try convincing zipapi.us this is their fault.Wert
Man, so open up security issues just to develop. Not a solution for the end product unless we will instruct all users to disable their security too.Jeremy

© 2022 - 2024 — McMap. All rights reserved.