2

I have a REST service that returns a JSON object. I am trying to make the authentication but it responses with empty data.

I did notice that the call is asychronous and when the user is pressing the login button it makes the call before getting the username and password. So I decided to use the $q constructor in order to fix it, but the problem consists, it still returns null data.

What am I doing wrong?

Thanks in advance.

factory

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

.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}));
        })
    };
}])

*****EDIT*****

I did change the code a little bit. I think the problem was how the $http was written.

factory

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})
        }   
    }
}])

It did somehow worked but it returns loginCheck:false. It seems that it does not recognize the correct username and password.

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

log:

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__()
9
  • Did you try debugging your service? You're sure that you're actually hitting the service? Does it log console.log("success!") or console.log("Error!!!")? Commented Aug 25, 2015 at 8:23
  • Yes, I did. When i did put the whole code into the controller the call was successful and returned the user's username. Now using factory it logs console.log("Error!!!") Commented Aug 25, 2015 at 8:30
  • So if you put your $http.post inside you controller, everything works just fine? Commented Aug 25, 2015 at 8:41
  • can you show result of console.log("Error!!!", response); Commented Aug 25, 2015 at 8:53
  • @Detilium yes, but I cannot use a button there unfortunately. Commented Aug 25, 2015 at 8:58

3 Answers 3

1

I figured it out. The login function was causing the problem $scope.login = function() so I used the $event object.

html

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

factory

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

.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}));
        })
    };
}])
Sign up to request clarification or add additional context in comments.

Comments

0

$http service is already returning a promise, so return it directly without using all the plumber :

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

        }   
    }

2 Comments

Thank you benek for your answer. I did tried that before but it responses null. I tried it now again but still nothing.
So it is not a problem of JS code, does your service return something in chrome/FF dev tool network panel ?
0

Try like this, anyway if you can show us your console log.

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;
                      });
                }   
            }
        }])

Change your controller like this:

.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
            }
    };
}])

11 Comments

Thanks Ivan for answering, I tried your way but now it says response = Object {data: "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Stric…rver Open Source Edition 4.1 </h3></body></html>", status: 400, config: Ob I think it does not understand the call
I did but the problem consists. POST http://localhost:8080/CashInRestServices_war/rest/user/login 415 (Unsupported Media Type) the log you asked for data = Object {username: "viewer", password: "viewer"}
Did you inject $httpParamSerializer? You are loging data instead ($httpParamSerializer(data)) i think
Did you mean this $httpParamSerializer(data) "password=viewer&username=viewer" ?
How is your server call implement? Have you documentation about that? Do you know if you need send the user and password securized? And if you need send the user and password like parameters or like headers?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.