Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works

Abhishek Savani
3 min readJun 14, 2021
cors error

Note: This solution is only for development purposes. for live application you can setup your own proxy at your server.

When you are working with the frontend this is a common error which you face. here we see how we can solve it using a proxy.

How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems

If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin header, you can still get things to work — by making the request through a CORS proxy.

The fastest fix you can make is to install the most CORS extension. Once installed, click it in your browser to activate the extension. Make sure the icon’s label goes from “Off” to “On”

Step: 1 Install this chrome extension.

Step: 2 Turn on the extension.

Step: 3 Hit this URL And Request temporary access to the demo server.

Request temporary access to the demo server.

Step: 4Now here you change your base URL.

if this is your base API URL. : —
https://abc.herokuapp.com/api/v1

Now add this Proxy URL: —
https://cors-anywhere.herokuapp.com

Now your final API endpoint is: —

https://cors-anywhere.herokuapp.com/https://abc.herokuapp.com/api/v1

The cors-anywhere server is a proxy that adds CORS headers to a request. A proxy acts as an intermediary between a client and a server. In this case, the cors-anywhere proxy server operates in between the frontend web app making the request, and the server that responds with data. Similar to the Allow-control-allow-origin plugin, it adds a more open Access-Control-Allow-Origin: * header to the response.

This solution is great because it works in both development and production. In summary, you’re taking advantage of the fact that the same origin policy is only implemented in browser-to-server communication. This means it doesn’t have to be enforced in server-to-server communication!

The one downside of the cors-anywhere proxy is that can often take a while to receive a response. The latency is high enough to make your applications appear a bit sluggish.

Conclusion

The CORS error can be the bane of the frontend developer. But once you understand the underlying same-origin policy behind the error, and how it fights the malicious cross-site request forgery attack, it becomes a little more bearable.

Ultimately, with these fixes, you’ll never have to break a sweat over seeing that red CORS error in your browser console logs again. Instead, in its face, you’ll whip out the plugin or a proxy

--

--