通过CORS政策

时间:2016-12-19 07:10:12

标签: javascript ajax

我从MDN读取CORS策略后尝试了所有功能,甚至使用了https://www.html5rocks.com/en/tutorials/cors/中的以下代码。我只是想获取一个wiki页面(给定)。它吐出错误消息,表明它运行onerror方法。在控制台我打印 “阻止跨源请求:同源策略禁止在https://en.wikipedia.org/wiki/Main_Page读取远程资源。(原因:缺少CORS标头'Access-Control-Allow-Origin'。”


// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('(.*)?')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
  // This is a sample server that supports CORS.
 // var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';
 var url = 'https://en.wikipedia.org/wiki/Main_Page';
  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}

1 个答案:

答案 0 :(得分:-3)

您可以使用iframe,

   document.getElementById(“iFrame”)。src =“https://en.wikipedia.org/wiki/Main_Page”;