雅虎财务api如何阻止原产地' null'来自javascript但接受地址栏请求?

时间:2016-11-29 04:14:52

标签: javascript google-chrome xmlhttprequest cors

当我在chrome中运行以下javascript时,我收到以下错误消息:No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {

    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // Otherwise, CORS is not supported by the browser.
    xhr = null;

  }
  return xhr;
}

var xhr = createCORSRequest('GET', "http://download.finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk");
if (!xhr) {
  throw new Error('CORS not supported');
}

xhr.send();

xhr.onload = function() {
 var responseText = xhr.responseText;
 console.log(responseText);
 // process the response.
};

xhr.onerror = function() {
  console.log('There was an error!');
};

但是当我直接从浏览器访问URL时,它会下载csv。这怎么可能,我如何在javascript中模拟浏览器请求来规避这个恼人的限制?

0 个答案:

没有答案