问题
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?
回答1:
just like @Bill Bilal said, i have to register it to my web.xml, so here is how i register it in my web.xml
<filter>
<filter-name>cors</filter-name>
<filter-class>com.myapp.springservice.utility.SimpleCORSFIlter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
回答2:
I had a similar CORS issue some time ago with a similar REST server. The headers were set in the REST server's base class, but it didn't seem to work. The only way I was able to fix it was by adding the following lines to my .htaccess file.
<ifModule mod_headers.c>
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</ifModule>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
回答3:
You can fix your problem by using this filter. It works fine with Spring Restful
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
I found this on the post angularjs spring cross-origin request blocked
Hope this help.
来源:https://stackoverflow.com/questions/32587570/how-to-enable-cors-properly-in-spring-restfull-webservice