Skip to content

Instantly share code, notes, and snippets.

@jesperorb
Last active February 21, 2024 14:17
Show Gist options
  • Save jesperorb/6ca596217c8dfba237744966c2b5ab1e to your computer and use it in GitHub Desktop.
Save jesperorb/6ca596217c8dfba237744966c2b5ab1e to your computer and use it in GitHub Desktop.
Handle CORS Client-side

Handle CORS Client-side

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. This is set on the server-side and there is nothing you can do from the client-side to change that setting, that is up to the server/API. There are some ways to get around it tho.

Sources : MDN - HTTP Access Control | Wiki - CORS

CORS is set server-side by supplying each request with additional headers which allow requests to be requested outside of the own domain, for example to your localhost. This is primarily set by the header:

Access-Control-Allow-Origin

The header specifies which origins (domains/servers) the information can be accessed from. To enable CORS you usually set it to allow access from all origins with a wildcard (*):

Access-Control-Allow-Origin: *

or you can tell the server to serve content to specific domains, every other domain will be blocked from showing the content in a browser:

Access-Control-Allow-Origin: https://developer.mozilla.org

Bypass client-side for production

Proxy

WARNING: Great services, but you are dependent on these services to work, if they break or go down, so does your app

You can use a service that proxies your request and automatically enable CORS for your:

Then you have to call your API by prepending one of these URLs to your request, for example:

JSONP

WARNING: This isn't allowed on every API and may break when calling certain APIS

You can bypass CORS in production using JSONP which stands for JSON with Padding and is kinda also a 'hack'. But it is a widely used hack which many APIs support. You are not sending a pure JSON-request but you are wrapping your data in a function that gets evaluated. JSONP explained in the link below:

JSONP explained in layman terms @ Stack Overflow

jQuery $.ajax() JSONP

The simplest way to handle JSON is through the $.ajax()-function in jQuery as it handles the real dirty parts automatically:

$.ajax({
  method: 'GET',
  url: 'http://localhost:3000',
  dataType: 'jsonp', //change the datatype to 'jsonp' works in most cases
  success: (res) => {
   console.log(res);
  }
})

jQuery: Working with JSONP

fetch-jsonp library

There is no native implementation of JSONP in either XMLHttpRequest or fetch. If you want to use fetch you can use this 1kb library which handle JSONP with fetch:

fetch-jsonp @ GitHub

  1. Link the code in your index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.6/fetch-jsonp.min.js"></script>
  1. And use like fetch but with the function fetchJsonp:
fetchJsonp('http://localhost:3000')
  .then(res => res.json())
  .then(json => console.log(json));

Vanilla JavaScript jsonp

It can be done in regular JavaScript as well of course:

Bypass during development 🔨

WARNING: All users who uses your site must use this hack so this is only intended for bypassing temporarily and for testing during development. You can't assume it will work for your end users. This is just a client-side quick fix and it doesn't change the way the server handles the request. This will make your site work on your computer and every other browser that also has this extension installed.

If you have Chrome you can use a extensions which 'hacks' the response/request. Be sure to disable it when not testing as it can break other sites, GitHub have been known to have problems with this extension if you have it enabled when browsing or using GitHub.

Allow-Control-Allow-Origin: * @ Chrome Web Store

@v-jerkin
Copy link

The header you need is Access-Control-Allow-Origin, not Allow-Control-Allow-Origin.

@jesperorb
Copy link
Author

@jerrykindall
Wow, what a huge brainfart, don't know how that happened. Thanks, I have corrected it.

@yasahmed
Copy link

i guess that it's impossible to bypass CORS using Js library, if you use JSONP you face this error :

Uncaught SyntaxError: Unexpected identifier

@simonsankar
Copy link

I was using the cors-anywhere with great success until, the site im scraping, i think blocked it error(403). So i cloned the repo and hosted my own copy on heroku and that failed as well. Could they have blocked all heroku apps? I say this as I hosted a local copy of cors-anywhere on a random port (9999) and it worked. So shouldnt a remote version work as well?

@jesperorb
Copy link
Author

@yasahmed
What do you mean? Your error doesn't seem to have anything to do with CORS, you have typ in your code from what it sounds like?

@simonankar
Oh really? I haven't used it for a while. I will try and see If I can get the same error. What was the site you were accessing? So I can reproduce.

@morjuax
Copy link

morjuax commented Mar 11, 2019

wow, the https://cors-anywhere.herokuapp.com/, it helped me perfectly

@chrishham
Copy link

chrishham commented Mar 27, 2019

You can also check the open source program Bypass Cors , an installable Electron App (Windows/Mac/Linux), that lets you Bypass ALL CORS Restrictions permanently, by allowing you to set your own custom Headers (+Origin).

It is specifically designed to work with Web Apps and its perfect for Real Time Scraping.

Disclaimer: I am the author of the program.

@Unionindesign
Copy link

For @simonsanker and anyone else (including myself) who has gotten a 403 with the CORS anywhere app - I don't think they have blocked Heroku apps, but if you dig through the docs for CORS anywhere they have set a limit for deployed, production apps. This does not apply to requests in development coming from localHost (thank goodness for that!), but once you have deployed your app, it sounds like the expectation is that you would have built your own proxy and CORS anywhere is good for testing, or development. At the time of this comment, the limit for production apps using the CORS anywhere proxy is a generous 200 HTTP requests per hour. That should be ample for most...unfortunately learned that the hard way with the SEMRush api, which both does not allow CORS, but also breaks up their data into a a lot of small requests!

@infinitbility
Copy link

Read the below documentation when you want to bypass the CORS issue on localhost

https://infinitbility.com/solve-cors-issue-on-localhost

@pratikpc
Copy link

Looks like https://crossorigin.me/ no longer works

@SudhanPlayz
Copy link

Thank you so much. Really helpful

@OlympuJupiter
Copy link

This was good guide to resolve cors error. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment