我使用Restangular来使用REST API,即使我在开发者控制台上看到XHR请求成功,它也总是给我这个错误。
错误
{
"data":null,
"status":-1,
"config":{
"method":"GET",
"transformRequest":[null],
"transformResponse":[null],
"jsonpCallbackParam":"callback",
"headers":{"Accept":"application/json, text/plain, */*"},
"url":"http://localhost:8080/profile/v1/support/tickets"},
"statusText":""
}
Restangular API调用
angular.module('adf-widget-tickets-module-service',['restangular'])
.service('ticketCRUDService', function ($rootScope, Restangular, $http) {
Restangular.setBaseUrl('http://localhost:8080/profile/v1/support');
this.readTickets = function () {
Restangular.all('tickets').getList().then(function (response) {
var test = response.json;
console.log(test);
return test;
},function (err) {
console.error(JSON.stringify(err));
},function () {
console.log("loading......");
})
};
}
你能否告诉我,我在这里做错了什么?
更新
以下是我的REST端点的代码
@GET
@Path("tickets")
@Produces("application/json")
public Response getAllTickets(){
ArrayList<Ticket> allTickets = new ArrayList<>();
try {
allTickets = elasticAPI.getAllTickets();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return Response.ok(gson.toJson(allTickets), MediaType.APPLICATION_JSON_TYPE).build();
}
答案 0 :(得分:1)
为什么您的端点返回-1
状态代码?
Angular仅在:200
和299
/*
* A response status code between 200 and 299 is considered a success status and will result in
* the success callback being called. Any response status code outside of that range is
* considered an error status and will result in the error callback being called.
* Also, status codes less than -1 are normalized to zero. -1 usually means the request was
* aborted, e.g. using a `config.timeout`.
* Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
* that the outcome (success or error) will be determined by the final response status code.
*/
https://github.com/angular/angular.js/blob/master/src/ng/http.js#L457
答案 1 :(得分:0)
正如我猜测问题不在我的客户端代码上。正因为如此,请求因CORS而被拒绝服务器。为CORS支持设置适当的响应头可以解决问题。