我在 Angular
应用程序中创建了一个基本身份验证系统,该系统是针对硬编码凭据编写的 - 见下文:
app.js
/* global app:true */
/* exported app */
'use strict';
/**
* @ngdoc overview
* @name WebAppApp
* @description
* # WebAppApp
*
* Main module of the application.
*/
var app = angular
.module('WebAppApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
controllerAs: 'login'
})
.when('/home', {
templateUrl: 'views/home.html'
//controller: 'loginCtrl',
//controllerAs: 'login'
})
.otherwise({
redirectTo: '/'
});
});
登录.html
<form ng-submit="submit()">
Username: <input type="text" id="username" ng-model="username" /><br>
Password: <input type="password" id="password" ng-model="password" /><br>
<input type="submit" value="Submit" />
</form>
登录.js
'use strict';
//app global variable
//this is hte controller that handles post requests
app.controller('loginCtrl', function ($scope, $location) {
$scope.submit = function(){
var uname = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin'){
$location.path('/home');
} else {
alert('username or password is wrong');
}
};
});
这有效。我现在想做的是,通过将数据发布到服务器/login 来检查 api 调用的用户名和密码,如果成功,将返回访问 token ,然后将其存储在 cookie 中。此时用户可以访问应用程序的其余部分。
如果凭据失败,则会进行验证以阻止用户登录。
最好的方法是什么?
最佳答案
首先检查这个url
你的代码看起来像这样:
$scope.submit = function(){
$http.post('/login', {
username:$scope.username,
password:$scope.password
}).then(function(response) {
if (response.data=="ok") {
//Login was ok
$location.path("/home");
} else {
//Login was not ok
}
}, function(response) {
//Error happend, response.status or response.statusText have details
});
}
关于javascript - 针对 Restful API 的 Angular 登录/身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31818654/