Cross-origin (CORS) error and Access-Control-Allow-Origin header

If the following error in the console causes you a sense of irritation, then you probably need a solution. This is a matter that often discouraged me from using the API. I didn’t know why. I read the documentation and did not understand. In the end I realized why my API was not working and I said goodbye to the problem once and for all. 🙂

Cross Origin Policy Error API CORS

Cross-origin Error is not because of your code

If you ask yourself “what am I doing wrong” then stop immediately. You do everything right, but you probably work on localhost with other protocol, host or port than API’s origin. Look, here is my code:
CORS API error cross-origin policy

It doesn’t look like anything is wrong here, right? This is a component of the application written in React. Axios makes it very easy to get data from an API. The application would work properly if the API wanted to work together. Here’s the error we have:

Request for resource of another origin blocked: “Same Origin Policy” does not allow to load remote resources from “” (missing “Access-Control-Allow-Origin” CORS header) .

Of course, after reading the error, I modified the code by adding a header to the query, but it did nothing. This is because the missing CORS “Access-Control-Allow-Origin” header should be in the server’s response and not in your query. So the API is working properly and your code is also valid. The problem will not be solved as long as you put the project on a server under an SSL certified domain (protocol) or change proxying.

Immediate solution – how to bypass the Cross-origin Error to build the application locally with the API

Don’t try to find a way to generate an SSL certificate for your local host. Also, do not test the application by uploading it to the server or github every now and then. There is a much faster, proven way, which is the browser plug-in.

These plugins allow the use of CORS because they add a header to the response to the query. For safety, I recommend that you keep them off and use them only when creating the project.

If you want to investigate the problem of the error, then go to the React documentation on Cross-origin errors.

Oceń artykuł