【问题标题】:AngularJS $http get return null status 0AngularJS $http 获取返回空状态 0
【发布时间】:2017-05-13 11:33:04
【问题描述】:

我正在尝试创建 $http get 请求以获取我的 Web 服务生成的一些 json 数据,但它返回 null 错误。但是,当我改用 sample url 时,$http 请求工作正常(它也返回 json 字符串)

这是我的角度代码:

angular.module('ionicApp', ['ionic'])

.controller('ListCtrl', function ($scope, $http) {
  $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

  $http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
   .then(function(response) {
       console.log("success ");
   }, 
   function(response) {
       console.log("Error : " + response.data + " Status : " + response.status);
   }
});

这是我的网络服务代码:

@GET
@Path("/GetUserList")
@Produces("application/json")
public Response GetUserList() throws SQLException {

  net.sf.json.JSONObject json = new net.sf.json.JSONObject();       
  JSONObject obj1 = new JSONObject();    
  JSONObject obj2 = new JSONObject();  
  JSONObject outerObject = new JSONObject();   
  JSONArray arr = new JSONArray();        

  obj1.put("Name", "Sara");
  obj2.put("Name","David");              
  arr.add(obj1);
  arr.add(obj2);

  outerObject.put("records", arr);

  return Response.status(200).entity(outerObject.toString()).build();
}

当我运行上面的代码时,它会返回这样的 json 字符串:

{"records":[{"Name":"Sara"},{"Name":"David"}]}

控制台日志返回:

Error : null Status : 0

null 错误是什么意思?或者我如何返回 json 字符串有什么问题吗?

【问题讨论】:

  • 尝试POSTMAN 验证响应。
  • 你的后端有 Spring 吗?
  • @RohitJindal 我使用了POSTMAN,它返回{"records": [{"Name": "Sara"},{"Name": "David"}]}。显示的状态为 200 OK。
  • 太好了。那么,您能否将第二个函数参数从response 更改为error 并将这个"Error : " + error.data + " Status : " + error.status 放在console.log 中。
  • @RohitJindal 试过了。控制台日志仍然显示相同的错误Error : null Status : 0

标签: java angularjs arrays json


【解决方案1】:

尝试使用JSON_STRINGIFY,这会将您传入的数据转换为字符串格式。

console.log(JSON_STRINGIFY(response.data));

要验证您的网络服务返回什么数据,您可以随时通过postman 访问您的网络服务来检查它。

【讨论】:

  • 我试过这个console.log("Error : " + JSON.stringify(response.data));,它仍然返回错误:null
  • 首先尝试通过 postman 访问您的 url /web 服务,它是一个 chrome 扩展,如果您对它返回的结果感到满意,则意味着角码有问题。请验证并告诉我
  • 尝试使用@GET @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
  • 在您的网络服务中。这应该可以解决您的问题
  • 我使用邮递员调用我的网络服务网址,就像你提到的那样,它返回:{"records": [{"Name": "Sara"},{"Name": "David"}]}
【解决方案2】:

我设法通过基于another SO answer 将 CORS (Access-Control-Allow-Origin) 添加到响应标头来解决这个问题。我的 Angular 代码没有问题,只是我需要修改我的 Web 服务代码以启用 CORS。

所以我只是修改了它返回数据的部分,变成这样:

return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

【讨论】:

    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 2015-01-24
    • 2017-01-16
    • 2013-07-29
    • 1970-01-01
    • 2014-10-19
    • 2023-04-04
    • 2013-10-21
    相关资源
    最近更新 更多