AngularJS $http REST 调用 returns 空数据

AngularJS $http REST call returns null data

我有一个 returns 一个 JSON 对象的 REST 服务。我正在尝试进行身份验证,但它以空数据响应。

我确实注意到调用是异步的,当用户按下登录按钮时,它会在获取用户名和密码之前进行调用。所以我决定使用 $q 构造函数来修复它,但问题在于,它仍然是 returns 空数据。

我做错了什么?

提前致谢。

工厂

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', '$q', function($http, $q) {

    return {
    login: function(username, password) {
        var deferred = $q.defer();

        $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: password})
            .then (function(data, status, headers, config){
                deferred.resolve(data);
            }, function(data, status, headers, config) {
                deferred.reject(data);
            })
        return deferred.promise;
        }   
    }
}])

控制器

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = function() {
        User.login($scope.username ,$scope.password)
            .then(function(response) {
                console.log("success!");
                $scope.status = response.status;
                $scope.data = response.data;
                $scope.username = response.username;
                alert("Success!!!    " + JSON.stringify({data: response.data}));
        }, function (response) { 
                $scope.data = response.data || "Request failed";
                $scope.status = response.status;
                console.log("Error!!!");
                alert( "failure message: " + JSON.stringify({data: response.data}));
        })
    };
}])

*****编辑*****

我确实稍微更改了代码。我认为问题在于 $http 的编写方式。

工厂

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', function($http) {
return {
    login: function(username, password) {
return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
        }   
    }
}])

它确实奏效了,但 returns loginCheck:false。好像没有识别正确的用户名和密码。

response = Object {data: Object, status: 200, config: Object, statusText: "OK"}

日志:

Object {data: Object, status: 200, config: Object, statusText: "OK"}config: Objectheaders: Objectmethod: 

"POST"paramSerializer: (b)password: "viewer"transformRequest: Array[1]transformResponse: Array[1]url: "http://localhost:8080/CashInRestServices_war/rest/user/login"username: "viewer"__proto__: Objectdata: ObjectloginCheck: false__proto__: 

Objectheaders: (c)arguments: (...)caller: (...)length: 1name: ""prototype: Objectconstructor: (c)__proto__: Object__proto__: ()<function scope>ClosureClosureGlobal: Windowstatus: 200statusText: "OK"__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()

constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()

$http 服务已经 returning 了一个承诺,所以 return 直接使用它而无需使用所有管道工:

login: function(username, password) {
       return $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: username});

        }   
    }

像这样尝试,无论如何,如果你能向我们展示你的控制台日志。

angular.module('myApp', ['ngRoute'])

        .factory('User', ['$http', function($http) {

            return {
                login: function(username, password) {
                    var myUrl = 'http://localhost:8080/CashInRestServices_war/rest/user/login';

                    var data = {
                        username: username,
                        password: password
                    };

                    return $http({
                        url: myUrl,
                        method: 'POST',
                        data: JSON.stringify(data),
                        headers: {
                             'Content-Type': 'application/json'
                        }
                      }).then(function(response) {
                           return response;
                      });
                }   
            }
        }])

像这样更改您的控制器:

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = login;

    ////////////////////
    function login() {
        User.login($scope.username ,$scope.password)
            .then(function(response) {
                $scope.status = response.status;
                $scope.data = response.data;
                $scope.username = response.data.username; // I dont know if response.data.username exists but i am sure that response.username doesn't
            }
    };
}])

我明白了。登录功能导致了问题 $scope.login = function() 所以我使用了 $event 对象。

html

<div><button ng-click="login($event)" type="submit">Login</button></div>

工厂

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', function($http) {

    return {
        login: function(username, password) {
        // return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
            var data = {username: username,password: password};
            console.log(JSON.stringify(data));
            return $http({
                method:'post', 
                url: 'http://localhost:8080/CashInRestServices_war/rest/user/login',
                data: JSON.stringify(data),
                headers: {'Content-Type': 'application/json'}
            })
        }
    }
}])

控制器

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = function(event) {
        event.preventDefault();

        User.login($scope.username ,$scope.password)
            .then(function(response) {
                $scope.status = response.status;
                $scope.data = response.data;
                alert(JSON.stringify({data: response.data}));
        }, function (response) { 
                $scope.data = response.data || "Request failed";
                $scope.status = response.status;
                alert( "failure message: " + JSON.stringify({data: response.data}));
        })
    };
}])