what i trying to achieve is consume my spring restful web service in another domain, but when i excute the json url that generated JSON value, my javascript console generate this error :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/SpringServiceJsonSample/service/updatepool/1. (Reason: CORS header 'Access-Control-Allow-Origin' missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/SpringServiceJsonSample/service/updatepool/1. (Reason: CORS request failed).
Here is my JSON value that generated by these link http://localhost:8080/SpringServiceJsonSample/service/updatepool/1
{"userid":1,"firstName":"brand","lastName":"bennet","email":"benjie@gmail.com"}
Here is my SpringController.java :
@RestController
@RequestMapping("/service/updatepool/")
public class SpringServiceController {
UserService userService = new UserService();
@RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(@PathVariable int id) {
User user=userService.getUserById(id);
return user;
}
}
Then i create SimpleCORSFilter based spring.io tutorial, so here is my SimpleCORSFilter.java class
@Component
public class SimpleCORSFIlter implements Filter{
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Here is how i consume the JSON value, first of all i create index.html file which is looked like index.html
<html ng-app>
<head>
<title>Angular Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>User ID : {{greeting.userid}}</p>
<p>firstName : {{greeting.firstName}}</p>
<p>lastName : {{greeting.lastName}}</p>
<p>email : {{greeting.email}}</p>
</div>
</body>
</html>
and here is my app.js
function Hello($scope, $http) {
$http.get('http://localhost:8080/SpringServiceJsonSample/service/updatepool/1').
success(function(data) {
$scope.greeting = data;
});
}
i already create the CORS filter class why it still give me CORS blocked error? which i missed? i don't think that class is working properly, how do i have to trace the error?