我正在向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?