Ajax请求返回纽约时报API间歇性故障

Ajax请求返回纽约时报API间歇性故障

本文介绍了CORS错误 - Ajax请求返回纽约时报API间歇性故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出几个Ajax请求的,同时迭代区的阵列(1至5)。我只能够在平均成功返回2请求,剩下的返回:

XMLHtt prequest无法加载https://api.nytimes.com/svc/politics/v3/us/legislative/congress/members/house/OR/2/current.json?api-key=xxxxxxx.
无访问控制允许来源标头的请求的资源present。原产地的http://本地主机:9001'。因此不允许访问

似乎没有图案到这些缺陷。即使使用相同的 _district 若干多次失败看似随机。

我的code:

  VAR title_element,
    title_render,
    district_numbers = ['1','2','3','4','5'],
    element_ids = ['ushd1','ushd2','ushd3','ushd4','ushd5'],
    apiKey ='API密钥= XXXXXXXXXXX',
    的baseUrl ='https://api.nytimes.com/svc/politics/v3/us/legislative/congress/members/house/OR/',
    orUsHouseMembers,
    FRAG;  对于(VAR I = 0,total_districts = district_numbers.length; I< total_districts;我++){
      (函数(ⅰ){
        VAR myUrl = +的baseUrl district_numbers [I] +'/current.json? + apiKey;        $阿贾克斯({
          网址:myUrl,
          数据类型:JSON,          成功:功能(数据){
            的console.log('\\ nSUCCESS:'+ myUrl);
            title_element =的document.getElementById(element_ids [I]);
            title_render = document.createTextNode(data.results [0]。名称+' - 区'+ data.results [0]。区);
            title_element.appendChild(title_render);
          },          错误:功能(数据){
            的console.log('\\ nFAIL:'+ myUrl);
          }
        })
      })(一世);
  }

我尝试添加访问控制允许来源:'*'和所有常见的CORS的东西,但我不希望这是一个真正的CORS问题,因为失败是太间歇

时的东西在我的code不妥或可能的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).

这篇关于CORS错误 - Ajax请求返回纽约时报API间歇性故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:30