如何检测ajax错误是否为Access-Control-Allow-Origin或文件实际上是否丢失

时间:2014-04-08 23:01:26

标签: javascript jquery ajax

我的问题不是如何解决Access-Control-Allow-Origin问题。执行请求时有时会发生此错误,有时网址可能已过时。但我想根据不同的错误为用户打印不同的消息。

目前我有以下代码:

$.ajax(
{
    url: link,
    type:'HEAD',
    timeout: 2000,
    error: function(request, status, message)
    {
        console.log('ajax error');
        console.log(request);
        console.log(status);
        console.log(message);
        openPopUp("There was an error accessing the image. It can be because the address is invalid, "+
            "or because the server where the image is stored is not allowing direct access to the images.");
    },
    success: function()
    {
        // More stuff here
    }
});

查看控制台,很容易看出文件是否实际丢失,或者是否是Access-Control问题。但我想打印两个不同的消息给用户说明问题究竟是什么。查看错误中的变量:函数(请求,状态,消息)它们不会更改,两种情况都会导致404错误。是否有其他人这样做,以便我可以知道问题是什么?

提前感谢您的关注。

2 个答案:

答案 0 :(得分:3)

您的浏览器控制台会显示

  

XMLHttpRequest无法加载http://www.google.com/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许来源“http://mysite.com”访问。

但是您无法仅使用JavaScript自行访问此信息。当浏览器检测到CORS违规时,它将discard the header information作为协议问题。

一个有效的解决方案是使用服务器端代码检查响应标头,并将结果传递回客户端页面。例如,如果ajax请求失败,您可以调用此脚本(让我们称之为cors.php)并确定它是否包含“Access-Control-Allow-Origin”。

示例:

  

cors.php URL = HTTP://ip.jsontest.com
  cors.php URL = HTTP://www.google.com

返回

  

Access-Control-Allow-Origin:*
  无

因此,您可以在JavaScript代码中执行以下操作:

$.ajax({
  url: "http://www.google.com",
  timeout: 4000,
  statusCode: {
    404: function() {
      // Simple not found page, but not CORS violation
      console.log(this.url + " not found" );
    }
  }
})
.fail(function(jqXHR, textStatus) {
   // Empty status is a sign that this may be a CORS violation
   // but also check if the request timed out, or that the domain exists
   if(jqXHR.status > 0 || jqXHR.statusText == "timeout") {
      console.log("Failure because: "+jqXHR.status+" "+jqXHR.statusText+" error"); 
      return;
   }

   // Determine if this was a CORS violation or not
   console.log("Checking if this is a CORS violation at - " + this.url);
   $.ajax({
      url: "http://myserver.net/cors.php?url=" + escape(this.url),
   })
   .done(function(msg) {
      // Check for the Access-Control-Allow-Origin header
      if(msg.indexOf("Access-Control-Allow-Origin") >= 0) {
        console.log("Failed bacause '" + msg + "'");
      } else {
        console.log("Failed bacause of CORS violation");
      }
   });
})
.done(function(msg) {
  // Successful ajax request
  console.log(msg);
}); /* Drakes, 2015 */

根据自己的需要自定义此PHP脚本:

<?php 
/* cors.php */

$url = $_GET["url"];
if(isset($url)) {
    $headers = getHeaders($url, "Access-Control-Allow-Origin");
    header("Access-Control-Allow-Origin: *"); // Allow your own cross-site requests
    echo count($headers) > 0 ? $headers[0] : "None";
}

// Get the response headers, only specific ones
function getHeaders($url, $needle = false) {
    $headers = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // Only get the headers
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header_line) use(&$headers, $needle) {
        if(!$needle || strpos($header_line, $needle) !== false) {
            array_push($headers, $header_line);
        }
        return strlen($header_line);
    });
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_exec($ch); 
    return $headers;
} /* Drakes, 2015 */

答案 1 :(得分:-1)

您应该能够从请求对象中读取响应头:

var acao = request.getResponseHeader('Access-Control-Allow-Origin');

然后根据标头是否存在以及您的网址是否为值来输出相应的错误。