I have a problem when trying to perform authentication with Ionic and AngularJs with a Backend in Cakephp 3. Testing with Chrome Postman, everything works perfect. The problem is making the call with the Ionic driver. Here I present all the elements in question:
// controllers.js
.controller('AuthCtrl', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginData = {};
$scope.loginError = false;
$scope.loginErrorText;
$scope.doLogin = function() {
var credentials = {
username: $scope.loginData.username,
password: $scope.loginData.password
}
var header = {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
}
$auth.login(credentials).then(function() {
$http.post('http://fullday-backend/api/users/token', header).success(function(response) {
var user = JSON.stringify(response.user);
localStorage.setItem('user', user);
$rootScope.currentUser = response.user;
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.coupons');
}).error(function() {
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
console.log($scope.loginErrorText);
console.log("error");
})
});
}
})
// App.js
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$authProvider.loginUrl = 'http://fullday-backend/api/users/token';
$stateProvider
.state('app.auth', {
url: '/auth',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'AuthCtrl'
}
}
})
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html'
}
}
})
.state('app.coupons', {
url: '/coupons',
views: {
'menuContent': {
templateUrl: 'templates/coupons.html',
controller: 'couponsCtrl'
}
}
})
.state('app.single', {
url: '/coupons/:couponId',
views: {
'menuContent': {
templateUrl: 'templates/coupon.html',
controller: 'couponCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/coupons');
});
PS: It is important to note that when sending incorrect user data and the password, you reject the connection with the code 401 correctly.