Reputation: 65
the service is working on spring But when i try to call a service in angular , the result object is empty and nothing is returned
service code :
public class CalculatorController {
@CrossOrigin(origins = "http://localhost:8090")
@GetMapping("/calc/{number1}/{number2}")
public Calculator calc(@PathVariable int number1,
@PathVariable int number2){
Calculator c = new Calculator(number1 , number2) ;
return c;
}
}
controller js code :
angular.module("myApp", [])
.controller("myCtrl", function($scope , $http) {
$http.get('http://localhost:8090/calc/5/8').
then(function (response)
{ $scope.result = response.data; }) ;
});
html code :
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Hello AngularJS</title>
<script src="moule.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-controller="myCtrl">
<p><span class="add">add is {{ result.add }}</span></p>
<span class="sub">sub is {{ result.sub }}</span>
</div>
</body>
</html>
thanks in advance
Upvotes: 1
Views: 200
Reputation: 3850
Your CORS filter (@CrossOrigin
) is set to http://localhost:8090
but seems like this is where your server side code reside. CORS should allow a source outside of your server to query your API, that means you need to provide your client side port information.
Lets say your server side runs on 8090
and your client on 8080
. Your filter on the server side should allow 8080
to use the API from a browser.
Try to change the CORS filter to match your client side not the server side.
Also, look in chrome debug tools (F12
) to see if you have a CORS exception.
More information about CORS:
Upvotes: 2
Reputation: 17299
it should be like this. you forgot add @ResponseBody
annotation for your method
@CrossOrigin(origins = "http://localhost:8090")
@GetMapping("/calc/{number1}/{number2}")
@ResponseBody
public Calculator calc(@PathVariable("number1") int number1,
@PathVariable("number2") int number2){
Calculator c = new Calculator(number1 , number2) ;
return c;
}
}
Upvotes: 1