0

I need to make a GET request from an external link (the api), though I've continued to google and change my code accordingly but nothing is working..

These are some I've tried..

<script>
    $.getJSON('url-goes-here?' + dataString, function(json_data){
       alert(JSON.stringify(json_data));
</script>

..

<script>
     fetch("https://url-goes-here", {
          mode: 'no-cors'
        })
         .then(function(resp) {
           console.log(data.needed_total) // variables in api
         });
     .catch(function(err) {
       console.log('Fetch Error :-S', err);
     });
</script>

I've checked whether it's problem with the api itself through postman however works as should.

I also get this error in console

Uncaught 'ReferenceError: $ is not defined

my scripts are

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
snw123
  • 21
  • 4

1 Answers1

1

It's that simple:

fetch('https://sampledomain.com/api')
  .then(res => res.json())
  .then(res => {
    console.log(res);
  })
solimanware
  • 2,952
  • 4
  • 20
  • 40
  • Thank you, it stopped the errors above, but I'm now getting new ones ... Fetch API cannot load https:/url-of-api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. **Uncaught (in promise) TypeError: Failed to fetch** I tried putting the no-cors mode as I did above, but it didn't like that either – snw123 Aug 23 '17 at 01:20
  • some domains refuse to share its content to other domains you can read more about https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS if you want to give it a try and send us the url I don't mind to check it – solimanware Aug 23 '17 at 01:23
  • Try prepending `https://cors-anywhere.herokuapp.com/` to the URL, like this: `fetch('https://cors-anywhere.herokuapp.com/https://sampledomain.com/api')`. And for an explanation see https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource/42744707#42744707 – sideshowbarker Aug 23 '17 at 01:37
  • @Microsmsm I really appreciate that offer, though the api isn't mine. It's for the company I'm working for.. Just out of respect to them. _If it was mine, I wouldn't mind_ – snw123 Aug 23 '17 at 01:39