0

I'm trying to obtain a json object from an api endpoint using jquery and ajax. This is my code:

$.ajax({ url: 'https://this-specific-website.com/customers.json', type: 'GET', contentType: 'application/json' }).done((response)=> { console.log('HELLLLLO INSIDE response') console.log('response', response) })

I also tried the same with the $.getJSON like this:

$.getJSON('https://this-specific-website.com/customers.json', (response)=> { console.log('HELLO INSIDE response') console.log('response', response) })

but I keep getting the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Is there a way to fix this issue?

Thank you in advance!!

UPDATE:

I finally did get it to work. Instead of using jquery and ajax on the front end, I created a seperate .js file and used http.get() like this:

Calling a JSON API with Node.js

Parth Patel
  • 13
  • 1
  • 5
  • The server you are requesting the json from does not have CORS enabled. If they support JSONP then use that, otherwise you have to make the request on the backend. – Dustin Poissant Aug 15 '17 at 14:41
  • 1
    Perhaps [this answer](https://stackoverflow.com/a/20035319/1418118) can help – Jefferson Aug 15 '17 at 14:42
  • In order to consume a resource using CORS (Cross-origin resource sharing) the server should authorize your access. – Jota Santos Aug 15 '17 at 14:43
  • Maybe a duplicate! take a look at this https://stackoverflow.com/questions/43824511/fetch-error-no-access-control-allow-origin-header-is-present-on-the-requested/43824620#43824620 – Souhail Ben Slimene Aug 15 '17 at 14:48

2 Answers2

0

Use JSONP in case your server supports this, below is the sample. ALternative is do a call to servelet or PHP in same domain which do a backend call and return you the response to your normal AJAX (or AJAX JSON_P)

$.ajax({
     url:"testserver.php",
     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
     success:function(json){
         // do stuff with json (in this case an array)
         alert("Success");
     },
     error:function(){
         alert("Error");
     }      
});
amit wadhwani
  • 1,140
  • 1
  • 7
  • 12
0

You can not do a CORS request from the browser if the server you are requesting the JSON from does not have it enabled. You can try JSONP if they support that.

If you are running on a backend then you can do a server-to-server request and that should work.

For example if you are on a PHP server use:

<?php echo file_get_contents("https://this-specific-website.com/customers.json"); ?>
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32