访问控制 - 允许 - 产地错误试图让JSON产地、访问控制、错误、JSON

2023-09-10 21:34:18 作者:没有梦想何必远方

我想利用必应API给拉了回来拼写建议,但不断收到以下错误:

XMLHtt prequest无法加载的http://api.search.live.net/json.aspx?Appid=myIdWasHere&query=explotion&sources=spell.产地的http:// myWebServerNameWasHere 不受访问控制 - 允许 - 原产地允许

我看了几个帖子,看起来差不多的话大约CORS,但我还是有点模糊。我有什么错在下面的code?

  $。阿贾克斯({
  键入:GET,
  网址:http://api.search.live.net/json.aspx,
  数据类型:JSON,
  数据: {
        APPID:'< myIdWasHere>',
        查询:explotion,
        来源:拼
        },
  beforeSend:功能(XHR){
         xhr.setRequestHeader(访问控制 - 允许 - 起源,*);
    },
  成功:功能(数据){
    警报(数据);
    },
  错误:函数(MSG){
    警报(this.url +-failed));
  }
});
 

解决方案

CORS(http://www.w3.org/TR/cors/)是制造使用XmlHtt prequest跨域请求一个新望路。因为你正在从你的域api.search.live.net的请求时,它被认为是一个跨域请求。 CORS需要服务器端的支持才能工作;具体而言,冰需要包括一个特殊标头,指示跨域请求是允许的。

我的猜测是,必应API不允许跨域请求。为了提出一个要求是,应考虑使用JSON-P(http://en.wikipedia.org/wiki/JSON#JSONP)。从他们的文档,它看起来像冰不支持JSON-P。查阅回调枚举示例部分在这里:

http://msdn.microsoft.com/en-us/library/ dd250846.aspx

未限速下载速度无法达到外网带宽案例09版本

I'm trying to utilize the Bing API to pull back spelling suggestions, but keep getting the below error:

XMLHttpRequest cannot load http://api.search.live.net/json.aspx?Appid=myIdWasHere&query=explotion&sources=spell. Origin http://myWebServerNameWasHere is not allowed by Access-Control-Allow-Origin

I read a couple posts that looked similar, then about CORS, but I'm still a bit fuzzy. What do I have wrong in the below code?

$.ajax({
  type: 'GET',
  url: 'http://api.search.live.net/json.aspx',
  dataType: 'json',
  data: {
        Appid: '<myIdWasHere>',
        query: 'explotion',
        sources: 'spell'
        },
  beforeSend: function(xhr){
         xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
    }, 
  success: function(data) {    
    alert(data);
    },
  error: function(msg) {    
    alert(this.url + " -Failed"));
  }
});  

解决方案

CORS (http://www.w3.org/TR/cors/) is a newish way of making cross-domain requests using XmlHttpRequest. Since you are making a request from your domain to api.search.live.net, it is considered a cross-domain request. CORS requires server-side support in order to work; specifically, Bing needs to include a special header that indicates that cross-domain requests are allowed.

My guess is that the Bing API does not allow cross-domain requests. In order to make a request, you should instead look into using JSON-P (http://en.wikipedia.org/wiki/JSON#JSONP). From their documentation, it looks like Bing does support JSON-P. Check out the "Callback Enumeration Example" section here:

http://msdn.microsoft.com/en-us/library/dd250846.aspx