0

When I input this url, https://www.codewars.com/api/v1/code-challenges/valid-braces?access_key=apiKey (apiKey is a variable for the actual key), into my browser, I'm able to view the data presented in JSON. However, I continue to receive this error message in my console:

XMLHttpRequest cannot load https://www.codewars.com/api/v1/code-challenges/valid-braces?access_key=apiKey. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

Here's my current request:

$.ajax({
  type: 'GET',
  dataType: 'json',
  url: 'https://www.codewars.com/api/v1/code-challenges/valid-braces?access_key=apiKey',
  success: function(data) {
    console.log(data);
  },
  error: function() {
    console.log('failed');
  }
});  
  • 1
    Cross domain issue use `jsonp`..Normally the api should return CORS headers which allow cross domain access. – Susheel Singh Jul 06 '16 at 04:24
  • You are requesting something from a different domain so you need to requests cross-origin permissions. You need to use CORS. http://www.html5rocks.com/en/tutorials/cors/ – DottedT Jul 06 '16 at 04:30
  • @SusheelSingh changing the dataType from `json` to `jsonp` return a new error: `Uncaught SyntaxError: Unexpected Token :` –  Jul 06 '16 at 04:38
  • You need access to server either to use `jsonp` or `CORS` setup – Susheel Singh Jul 06 '16 at 04:47
  • How do I gain access? Shouldn't I have access to the server since I have the API key? –  Jul 06 '16 at 04:51

1 Answers1

0

The API should have Access-Control-Allow-Origin: http://yourdomain.com added on response header. * can be used to allow all domain.

How does Access-Control-Allow-Origin header work? talks about how it works

Update: using JSONP may not the right way but if you really need try this

$.ajax({
  url: 'https://www.codewars.com/api/v1/code-challenges/valid-braces?access_key=apiKey&callback=',
  dataType: 'JSONP',
  type: 'GET',
  async: false,
  crossDomain: true,
  success: function () {}, // don't use this, as this will never get executed
  error: function () {},  // don't use this, as this gets executed for each request
  complete: function (data) {
  //a hack to handle request status
    if (data.readyState == '4' && data.status == '200') {
     alert('SUCCESS');
    }
    else {
     alert('FAIL');
    }
  }
});
Community
  • 1
  • 1
j_k
  • 1
  • 3
  • I don't have direct control of the API, so how can I gain access for my domain? –  Jul 06 '16 at 04:36
  • changing the dataType from json to jsonp return a new error: Uncaught SyntaxError: Unexpected Token : –  Jul 06 '16 at 05:10