SERVICES.JS
app.service('AuthService', function ($q, $http) {
var LOCAL_TOKEN_KEY ='';
var username ='';
var isAuthenticated = false;
var authToken;
function loadUserCredentials() {
var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
if (token) {
useCredentials(token);
}
}
function storeUserCredentials(response) {
window.localStorage.setItem(LOCAL_TOKEN_KEY, response.meta.token);
useCredentials(response);
}
function useCredentials(response) {
username = response.data.username;
console.log(username);
isAuthenticated = true;
authToken = response.meta.token;
console.log(authToken);
$http.defaults.headers.common['Authorization'] = 'Bearer ' + response.meta.token;
}
function destroyUserCredentials() {
authToken = undefined;
username = '';
isAuthenticated = false;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + undefined;
window.localStorage.removeItem(LOCAL_TOKEN_KEY);
}
var login = function (email, password) {
return $q(function (resolve, reject) {
var params = {
email: email,
password: password
}
$http({ *****// this POST METHORD IS NOT*****
method: 'POST',
url: "http://107.170.112.247/brain/public/api/v1/login",
data: params,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
print : function(){
console.log(params);
}
}).then(function(response){
// console.log(response);
storeUserCredentials(response);
if (isAuthenticated)
resolve('Login success.');
else
reject('Login Failed.');
})
});
};
var logout = function () {
destroyUserCredentials();
};
loadUserCredentials();
return {
login: login,
//logout: logout,
isAuthenticated: function () {
return isAuthenticated;
},
};
})
.factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) {
return {
responseError: function (response) {
$rootScope.$broadcast({
401: AUTH_EVENTS.notAuthenticated,
403: AUTH_EVENTS.notAuthorized
}[response.status], response);
return $q.reject(response);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
CONTROLLER.JS
app.controller('loginCtrl', function($scope, $state, $ionicPopup, AuthService) {
$scope.data = {};
$scope.login = function(data) {
AuthService.login(data.email, data.password).then(function() {
console.log("kartik khandelwal");
$state.go('/home-menu', {}, {reload: true});
console.log("k");
}, function(err) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
};
});
请检查流量是否正确?
我的帖子请求方法没有执行!
对于显示的每个用户名和密码:
UNAUTHORIZED ACCESS 401 ERROR!
并且在检查用户名和密码时问题是它没有进入API的正确格式...