如何在javascript中通过url获取某些页面

如何在javascript中通过url获取某些页面,javascript,xmlhttprequest,cors,postman,Javascript,Xmlhttprequest,Cors,Postman,我想使用javascript从web站点获取页面。 我有如下网址: http://not-my-site.com/random 从“随机”我将被重定向到网站上的另一个随机页面。 邮递员做我想做的一切:它是得到整个网页的html。但是我如何在javascript中实现同样的功能呢? 我试着按照这个指南去做,但没有成功。我仍然得到一个错误: XMLHttpRequest cannot load http://not-my-site.com/random. No 'Access-Control-A

我想使用javascript从web站点获取页面。 我有如下网址:

http://not-my-site.com/random
从“随机”我将被重定向到网站上的另一个随机页面。 邮递员做我想做的一切:它是得到整个网页的html。但是我如何在javascript中实现同样的功能呢? 我试着按照这个指南去做,但没有成功。我仍然得到一个错误:

XMLHttpRequest cannot load http://not-my-site.com/random. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
教程中的代码:

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://not-my-site.com/random');
if (!xhr) {
  throw new Error('CORS not supported');
}

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

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

xhr.send();
我也尝试过像这样的普通xhr,但得到了相同的错误:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://not-my-site.com/random', true);
xhr.send();

这似乎是服务器上未正确配置CORS的问题。下面的PHP代码应该允许来自任何域的任何请求。如果您不使用PHP,那么将下面的代码转换成任何其他语言应该很容易,线索是写入HTTP头

请记住在输出任何HTML之前放置此代码

$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST'];
header('Access-Control-Allow-Origin: '.$origin);        
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With');
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"');
header('Access-Control-Max-Age: 1');

接受来自所有域的请求是不安全的。要获得更好但稍微更复杂的解决方案,请参见此处:

是否可以发布给出此错误的代码?如果是McVet,就没有额外的奖励了,cors没有什么可尝试的;要么远程站点实现了它,要么工作了,要么不工作了,除了在后面的例子中使用服务器端代理或像YQL这样的服务,你什么也做不了……最后,我使用了任何来源。工作很好。。。