I have a REST service. Which is having JWT authorization. To get the token, you need to send POST request to '/login' endpoint with JSON:
{
'username':'username',
'password':'password'
}
After that you receive JSON, for example:
{
'token': "a1a1.b2b2.c3c3"
}
I'm new to AngularJS and JavaScript itself, so I'm playing with basics for now. Just trying to get a token from login service.
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;
};
}]);
So when I open index.html it's getting me lol instead of JSON response that I'm expecting. Whats wrong with that?
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;
};
}]);