DEV Community

cigwe416
cigwe416

Posted on

11 4

Fix CORS Error (JavaScript)

What is CORS?

cors

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources - MDN

This definition might seem confusing so let me try to explain it in simpler terms.

CORS is a browser policy that allows you to make requests from one website to another which by default is not allowed by another browser policy called Same Origin Policy.

This is an error that is mostly addressed from the backend of an API.
The problem here is when you are trying to call a public API without the CORS error being fixed and you can't reach the developers that developed the API.

In this tutorial, I'll be showing you how to by-pass CORS errors using Vanilla Javascript when you are in such a situation.

The API we are going to be using is a Quote Generator API.

http://api.forismatic.com/api/1.0/

In other to get list of Quotes, we need to append this to the base URL

?method=getQuote&lang=en&format=json.

So the full URL becomes;

http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json

In other to make the API call, we need to create a Javascript file and call the endpoint.We would be using the fetch API.

This would look like this;



// Get quote from API
async function getQuote() {
  const apiUrl = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
  try {
     const response = await fetch(apiUrl);
     const data = await response.json();
     console.log({data});
  } catch (error) {
     console.log(error);
      }
  }
// On load
getQuote();


Enter fullscreen mode Exit fullscreen mode

If you run this code in your browser and open up your console, you should see the error below;

Screen Shot 2021-03-04 at 6.39.46 PM

In other to fix this error, add the following lines of code;



// Get quote from API
async function getQuote() {
  const proxyUrl = 'https://cors-anywhere.herokuapp.com/' -> this line;
  const apiUrl = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
try {

     const response = await fetch(proxyUrl + apiUrl) -> this line;
     const data = await response.json();
     console.log({data});
  } catch (error) {
     console.log(error);
      }
  }
// On load
getQuote();


Enter fullscreen mode Exit fullscreen mode

This URL https://cors-anywhere.herokuapp.com/ is also a public API that was created by someone to fix the CORS error.

N.B: You might still get some errors on your console even after following the steps I just showed.If this happens, go to this URL

   `https://cors-anywhere.herokuapp.com/corsdemo`
Enter fullscreen mode Exit fullscreen mode

and follow the instructions there.

Thanks for taking your time to read this Article. Your feedback and comment is highly welcomed.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (7)

Collapse
 
navidnourani profile image
NavidNourani

Thanks a lot <3

Collapse
 
deexter profile image
deexter

Fetch has no cors option, anyway you should not do this.

Collapse
 
cigwe416 profile image
cigwe416 • Edited

Yes you are right. This is just for development environment

Collapse
 
cindycc21 profile image
cindycc21

this doesn't work anymore (cors-anywhere.herokuapp.com) - is there another way to do this?

Collapse
 
wanmaoor profile image
wanmaoor

But what if I got to shift into production mode, I have to get rid of all of proxyUrl wherever ?😫😫😫😫

Collapse
 
cigwe416 profile image
cigwe416

It's not about a security issue. It's so that you won't be disappointed when the server cannot be reached. You are advised to create yours so you can effectively manage it.

Collapse
 
andaeiii profile image
Ande Caleb

9aice one Nonso... real nice...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more