So I'm using a third party API in my front-end application. I was having some CORS issues. Since it's a public API, I contacted the API maintainers to ask them to lift the CORS control. They've done it, seemingly by putting a *
to Access-Control-Allow-Origin
.
It would be perfect but... since this (old) API require authentification, it's using cookies and now I get this error (see title).
My application being in React, I'm using Axios
with a
myApiRequest.defaults.withCredentials = true;
line.
Is there any way to do it in a front-end application or is back-end the only way to do it ?
Thanks !
CodePudding user response:
Two problems require two different solution
Allowing the third party domain on your site
This is where you end up using CROS and ACAO. In a general sense, it controls which domain has access to this website be that loading a script or rending an image.
Cookie policy
You can control how your cookies are shared with third party domains or any JS code using cookie policy. Check about strict, lax.
But don't share the untrusted websites to access your cookies. As they request resources on behalf of a user.
Recommended approach
Try hitting doing server to server requests and use your server as a middle man to get all the data.
CodePudding user response:
According to this MDN:
To correct this problem on the client side, ensure that the credentials flag's value is false when issuing your CORS request.
Set your credential as false:
myApiRequest.defaults.withCredentials = false;
Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values.
Use XMLHttpRequest
requests separately in back-end as like this:
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);
oReq.open();
The answer to your question:
My question is : is there any other way to do this without using this non supported method ?
is: as, you are using the requests sent from server side, so you have to use it from supported methods only, no other ways.
Reading Links:
- Axios - No 'Access-Control-Allow-Origin' - CORS
- https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest