CORS Error - Ajax request returns intermittent fai

2019-08-09 04:03发布

I am making several ajax requests to the NYTimes Congress API, whilst iterating over an array of districts (1 to 5). I am only able to successfully return 2 requests on average, the rest returning a:

XMLHttpRequest cannot load https://api.nytimes.com/svc/politics/v3/us/legislative/congress/members/house/OR/2/current.json?api-key=xxxxxxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9001' is therefore not allowed access.

It appears that there is no pattern to these failings. Even using the same _district number multiple times fails seemingly randomly.

My code:

var title_element,
    title_render,
    district_numbers = ['1', '2', '3', '4', '5'],
    element_ids = ['ushd1', 'ushd2', 'ushd3', 'ushd4', 'ushd5'],
    apiKey = 'api-key=xxxxxxxxxxx',
    baseUrl = 'https://api.nytimes.com/svc/politics/v3/us/legislative/congress/members/house/OR/',
    orUsHouseMembers,
    frag;

  for (var i = 0, total_districts = district_numbers.length; i < total_districts; i++) {
      (function (i) {
        var myUrl = baseUrl + district_numbers[i] + '/current.json?' + apiKey;

        $.ajax({
          url: myUrl,
          dataType: 'json',

          success: function (data) {
            console.log('\nSUCCESS: ' + myUrl);
            title_element = document.getElementById(element_ids[i]);        
            title_render = document.createTextNode(data.results[0].name + ' - District ' + data.results[0].district );
            title_element.appendChild(title_render);
          },

          error: function (data) {
            console.log('\nFAIL: ' + myUrl);
          }
        })
      })(i);
  }

I tried adding Access-Control-Allow-Origin: '*' and all the usual CORS stuff, but I dont expect this to be a true CORS issue as the failures are too intermittent

Is something in my code amiss or maybe the API?

1条回答
走好不送
2楼-- · 2019-08-09 04:39

Is something in my code amiss or maybe the API?

Yes, instead of json, change the AJAX's dataType option to jsonp:

dataType: 'jsonp'

In order to avoid of CORS issues when you only want to GET data, use JSONP.


P.S:

Note that I tested it by myself in a small demo that I made using jsFiddle and it's working correctly, just take on account that it's now returns 403 (Forbidden) - I assume because I should enter a valid api-key, you provided a fake one (api-key=xxxxxxxxxxx).

查看更多
登录 后发表回答