When I first started using xhr requests I encountered the plight known as CORS, that naggy little error that boasts No ‘Access-Control-Allow-Origin’ header is present on the requested resource… Over the years dealing with the issue is a matter of just making things work, which working on a coding challenge I got the dreaded ‘there was an error with your code…’ email. Turns out it was the CORS proxy was being blocked by the firewall. In this blog post I will cover the three common workarounds (in order of ease, not logical order) for beating the Access-Control-Allow-Origin issue that oh so many frontend folks face.
JSONP works via the script tag to the page with a callback either specified as a query parameter or as part of the response (albeit improper JSON formatting). The script tag can be either a static tag on the page or added dynamically to the DOM.
CORS works by proxying the request and then modifying the Access-Control-Allow-Origin headers to (usually) *. By introducing the proxy into the mix the abstraction gets more complex and can result in inconsistent behavior.
The worst possible way to get data from one origin into a page is using an iframe to set the origin as needed, and then using postmessage to send the data as a string. While this is one of my least favorite ways to transmit data, it is also a solution that has its place.
The easiest way in the short term to resolve this issue is to install a browser pluggin that will proxy the requests with a * in the header. But this is only a short term solution, to be able to fully resolve the issue it must be traced back to the source on layer 4 of the OSI model (in Apache or Nginx or whatever is serving this layer).
Using the above workarounds are sometimes part of the job when it just needs to work. Having proper fallbacks that gave sufficient security permissions should all be encapsulated and tested for on a regular basis.