我有一个REST服务。哪个有JWT授权。 要获取令牌,您需要将POST请求发送到' / login'使用JSON的端点:
{
'username':'username',
'password':'password'
}
之后你会收到JSON,例如:
{
'token': "a1a1.b2b2.c3c3"
}
我是AngularJS和JavaScript本身的新手,所以我现在正在玩基础知识。只是试图从登录服务中获取令牌。
的index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>app</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="app.js"></script>
<script src="service.js"></script>
</head>
<body class="container" ng-controller="AppController as app">
<div ng-controller="ServiceController as service">
<p>{{service.login()}}</p>
</div>
</body>
</html>
app.js
(function () {
var app = angular.module('app',['service']);
app.controller('AppController', function () {
});
})();
service.js
angular.module('service', [])
.controller('ServiceController', ['$http', function ($http){
var url = 'http://localhost:8080/login';
var resp = 'lol';
var credentials = { 'username' : "username", 'password' : "password" };
this.getToken = function () {
return $http.post(url, credentials).success(function(response) {
angular.forEach(response.data.token, function(token) {
resp = token;
});
});
};
this.getToken();
this.login = function () {
return resp;
};
}]);
因此,当我打开index.html时,它让我大声笑而不是我期待的JSON响应。那有什么不对吗?
EDIT2:
service.js
angular.module('service', [])
.controller('ServiceController', ['$http', function ($http){
var url = 'http://localhost:8080/login';
var resp = 'lol';
var credentials = { 'username' : "username", 'password' : "password" };
$http.defaults.headers.common['Content-Type']= 'application/json';
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
*this.getToken = function () {
return $http.post(url, credentials).success(function(response) {
resp = response.data.token;
});
};*
this.getToken();
this.login = function () {
return resp;
};
}]);