我想从我的服务器访问 POST 方法,但是当我记录响应时,它总是返回 status=0,任何人都可以帮助我或给我建议? 注意:我已经在 Postman 中尝试了我的方法,它仍然有效
这是我的 Controller
nameApp.controller('loginCtrl', ['$scope','$location','Flash','$sessionStorage', '$cookieStore','$http',function (scope,location,Flash,sessionStorage,cookieStore,http) {
scope.nim='';
scope.pass='';
if(cookieStore.get('current')!=null){
location.path('/homepage')
}
scope.login = function() {
if((scope.nim=='')){
Flash.create('danger', 'Invalid Username / Password', 'custom-class');
}else{
http.post('http://localhost:8084/iec3/rest/users/login',{'username':'admin','password':'bukanadmin'},{headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
console.log("GREAT");
}, function errorCallback(response) {
console.log(response)
});
}
}
}]);
这是我 Controller 的登录方法
@Path("/login")
@POST
@Consumes(value = MediaType.APPLICATION_JSON)
@Produces(value = MediaType.APPLICATION_JSON)
public Response login(User user) {
UserDao ud = new UserDao();
User dariDB = ud.login(user.getUsername(), user.getPassword());
dariDB.setPassword("");
return Response.ok(dariDB)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.build();
}
这是我尝试记录响应时的错误
对象 {data:null, status:0, headers:dd/<(), config:Object, statusText:""}
最佳答案
您需要验证您的请求是否到达服务器。您的登录方法是否被调用?如果您在同一主机上,则无需传递完整的 url,您可以直接通过其路径调用您的 api。
对于新手,我建议您避免使用 $http
快捷方式。为了更好的理解和可读性,你应该使用 $http
like
$http({
method: 'POST',
url: 'http://localhost:8084/iec3/rest/users/login',
data: {
username:'admin',
password:'bukanadmin'
},
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log("GREAT");
}, function errorCallback(response) {
console.log(response)
});
关于javascript - 发出 AngularJS $http 请求 POST 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513592/