CORS错误 – 使用NYTimes API,Ajax请求返回间歇性故障
我正在向NYTimes Congress API提出几个ajax请求,同时迭代一系列区域(1到5)。 我只能平均成功返回2个请求,其余的返回:
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.
似乎这些失败没有模式。 即使多次使用相同的_district
数也看似随机失败。
我的代码:
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); }
我尝试添加Access-Control-Allow-Origin: '*'
以及所有常见的CORS内容,但我不认为这是一个真正的CORS问题,因为失败过于间歇
我的代码中的某些内容是错误还是API?
我的代码中的某些内容是错误还是API?
是的,而不是json
,将AJAX的dataType
选项更改为jsonp
:
dataType: 'jsonp'
为了避免在您只想GET
数据时出现CORS问题,请使用JSONP 。
PS:
请注意,我自己在一个使用jsFiddle进行的小型演示中测试了它并且它正常工作,只考虑它现在返回403 (Forbidden)
– 我假设因为我应该输入一个有效的api-key
,你提供了一个假的一个( api-key=xxxxxxxxxxx
)。