Access Control Origin Header error using Axios
Full error message
I'm making an API call using Axios in a React Web app. However, I'm getting this error in Chrome:
XMLHttpRequest cannot load
https://example.restdb.io/rest/mock-data. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
{
axios
.get("https://example.restdb.io/rest/mock-data", {
headers: {
"x-apikey": "API_KEY",
},
responseType: "json",
})
.then((response) => {
this.setState({ tableData: response.data });
});
}
I have also read several answers on Stack Overflow about the same issue, titled Access-Control-Allow-Origin but still couldn't figure out how to solve this. I don't want to use an extension in Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.
After trying out few answers I have tried with this,
headers: {
'x-apikey': '59a7ad19f5a9fa0808f11931',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
Now I get the error as,
Request header field Access-Control-Allow-Origin is not
allowed by Access-Control-Allow-Headers in preflight responseSolutionsource: stackoverflow \u2197
If your backend support CORS, you probably need to add to your request this header: headers: {"Access-Control-Allow-Origin": "*"} [Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server. But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS. You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/21c4259a782e3d68b5d7acfe356bfaa11c6e872dd8f3678d635199db6cfa30c0hash \u00b7 21c4259a782e3d68b5d7acfe356bfaa11c6e872dd8f3678d635199db6cfa30c0