Angular $ http.get和jQuery $ .getJSON错误,但URL在自己的选项卡中打开正常

时间:2014-02-15 05:08:09

标签: jquery ajax angularjs cors

我很难过。我正在尝试用名字做一个简单的客户查询请求。 jQuery.ajax()(来自控制台)和Angular的$http.get()都出错,但我不知道为什么。当我在另一个选项卡中打开给这些函数的相同URL时,它会显示预期的JSON响应。

的jQuery

$.ajax("http://[ip#]:8081/customerservice/customer/search?firstName=John", {
  "dataType": "json",
  "success": function() {
    alert("success");
    console.log("jQuery data", data);
  },
  "error": function(jqXHR, textStatus, errorThrown) {
    alert("error");
    console.log("jQuery jqXHR", jqXHR);
    console.log("jQuery textStatus", textStatus);
    console.log("jQuery errorThrown", errorThrown);
  },
  "complete": function(jqXHR, textStatus) {
    alert("complete");
    console.log("jQuery jqXHR", jqXHR);
    console.log("jQuery textStatus", textStatus);
  }
});

结果:错误和完整警报触发。 textStatus为“错误”,errorThrown为空字符串,jqXHR包含

readyState    0
responseText  ""
status        0
statusText    "error"

return $http.get('http://[ip#]:8081/customerservice/customer/search?firstName=John',
    {
        responseType: "json"
    }
)
.success(function(data, status, headers, config){
    alert("angular success");
})
.error(function(data, status, headers, config){
    alert("angular error");
    console.log(status);
    console.log(headers());
    console.log(config);
})
;

结果我在Firebug中看到一个带有给定URL的“200 OK”和响应时间。 status 是404, headers()返回一个空对象,而配置对象是

headers           Object { Accept="application/json, text/plain, */*"}
Accept            "application/json, text/plain, */*"
method            "GET"
responseType      "json"
transformRequest  [function()]
    0
    function()
transformResponse [function()]
    0
    function()
url               "http://[ip#]:8081/customerservice/customer/search?firstName=John"

Firebug也显示

Response Headers
Content-Type    application/json
Date    Sat, 15 Feb 2014 05:13:02 GMT
Server  Apache-Coyote/1.1
Transfer-Encoding   chunked

Request Headers
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
DNT 1
Host    [ip#]:8081
Origin  http://127.0.0.1
Referer http://127.0.0.1/
User-Agent  Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0

其他信息我在虚拟机中运行此功能,但我仍然可以直接访问互联网和[ip#]。我是Angular的新手,这就是我用jQuery尝试它的原因。

那么,发生了什么?我在Angular UI Typeahead示例中构建了它,并且它与Google地理编码URL一起运行良好。是因为我使用的是IP#和/或端口吗?是不是我看不到的东西?

更新:已添加CORS标头,现在jQuery正常工作,但Angular正在提供404。它似乎是默认发送的X-Requested-With标题was a problem with CORS in 1.1,但我使用的是1.2。

的jQuery

$.post(
    "http://[ip#]:8081/customerservice/customer/search",
    "firstName=John&lastName=Smith",
    function (data, textStatus, jqXHR) {
      console.log("success!", data);
    }
);

$http.post("http://[ip#]:8081/customerservice/customer/search",
        "firstName=John&lastName=Smith"
    )
    .success(function(data, status, headers, config) {
        $scope.result = data;
    })
    .error(function(data, status, headers, config) {
        $scope.result = data || "Request failed";
        console.log("status: ", status);
        console.log("headers: ", headers());
        console.log("config: ", config);
    })
;

1 个答案:

答案 0 :(得分:0)

正如Arun P JohnyBrian Vanderbusch指出的那样,这是一个CORS问题。

添加Access-Control-Allow-Origin标头允许jQuery响应开始工作。

但是,“$ http服务会自动为所有请求添加某些HTTP标头”[“Setting HTTP Headers”,AngularJS docs]。在这种情况下,它是一个Content-Type标头,它导致了另一个CORS问题:OPTIONS ... Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

这并没有出现在Firebug和Firefox的控制台中。直到我尝试Chrome,我才得到任何输出来帮助调试。

解决方案是:

  1. Content-Type添加到Access-Control-Allow-Headers(请参阅注释)或
  2. 从请求中删除默认Content-Type标头,类似于this answer

    myApp.config(function($httpProvider){
        delete $httpProvider.defaults.headers.post['Content-Type'];
    });
    
  3. 注意:我的开发人员已指定Access-Control-Allow-Headers x-requested-with,因此我不知道该单个条目是否否定所有其他条目,或者是否需要以任一方式指定Content-Type