0

Hi I'm new to javascript and API calls and I'm trying to make an API call using the following javascript code:

var url = 'https://labs.bible.org/api/? 
passage=random&type=json&callback=myCallBackFcn';

var ourRequest = new XMLHttpRequest();

ourRequest.open('GET', url);

ourRequest.onload = function(){
  console.log(ourRequest.responseText);
};

ourRequest.send();

When I refresh my page I get the following error:

Failed to load https://labs.bible.org/api/?passage=random&type=json&callback=myCallBackFcn: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Can anyone help me with this? Also, can you explain exactly how to fix it?

mx0
  • 6,445
  • 12
  • 49
  • 54
Jrobm2k9
  • 73
  • 2
  • 8

1 Answers1

1

You have a cross-origin issue, let's explain it.

Browser downloaded js file from example.com website, now js file wants to make ajax to xyz.org website, this is a cross-origin request and so the browser asks xyz.org "do you allow example.com to access your resources"? the browser knows the answer from 'Access-Control-Allow-Origin' Response header.

But xyz.org didn't send this header so the browser assumed xyz.org doesn't want anyone but him to access his resources so the browser just refuses your request.

Note that cross-origin request happens too when you access js file in a URL beginning with file:// and origin here is set to null because js isn't downloaded from any server yet origin null is different from xyz.org.

Solution: if you control xyz.org just make it add Access-Control-Allow-Origin to response headers, you can look the internet for value format for this header.

If it's a third party website you have to call its admins and if they refuse to add the header then you simply have no solution in pure js but hey only browsers respects this policy, if you make a desktop application then it doesn't care and an example of this is Postman the REST APIs tester.

niceman
  • 2,653
  • 29
  • 57
  • Hello even I am encountering the same issue. even though I have header configured. Can you please help? My related config files are provided in this link https://stackoverflow.com/questions/56610107/integrate-two-docker-apps-docker-compose-and-docker-run/56616067#56616067 – The Great Jun 18 '19 at 06:09