AngularJS $ http获取返回null状态0

时间:2016-12-29 06:58:42

标签: java angularjs arrays json

我正在尝试创建$ 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字符串有什么问题?

2 个答案:

答案 0 :(得分:1)

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

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

要验证您的网络服务返回的数据,您可以随时通过postman点击您的网络服务进行检查。

答案 1 :(得分:0)

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

所以我只修改了返回数据的部分,如下所示:

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