【问题标题】:How to get some page by url in javascript如何在javascript中通过url获取一些页面
【发布时间】:2015-02-04 22:43:55
【问题描述】:

我想使用 javascript 从网站获取页面。 我有这样的网址:

http://not-my-site.com/random

从“随机”我将被重定向到网站上的另一个(随机)页面。
邮递员做我想做的一切:) 它得到整个页面(html)。但是我怎样才能从 javascript 中做同样的事情呢?
我已经按照本指南http://www.html5rocks.com/en/tutorials/cors/ 尝试了 CORS,但没有成功。我仍然只是得到一个错误:

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();

【问题讨论】:

  • 能否请您发布出现此错误的代码? (如果是 MCVE 则额外奖励)
  • cors 没什么可尝试的;远程站点要么实现它并且它可以工作,要么它不工作,除了在后一种情况下使用服务器端代理或 YQL 之类的服务之外,您无能为力...
  • 最后,我使用了任何来源。工作正常...stackoverflow.com/questions/15005500/…

标签: javascript xmlhttprequest cors postman


【解决方案1】:

这似乎是服务器上没有正确配置 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');

接受来自所有域的请求是不安全的。如需更好(但稍微复杂一点)的解决方案,请参阅此处:CORS That Works In IE, Firefox, Chrome And Safari

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 2016-10-06
    • 2011-05-03
    • 2016-05-20
    • 1970-01-01
    • 2021-08-08
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多