I facing issue with CORS in spring boot. I have configured CORS like this
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
which I suppose enables all header and other stuff.
It works excellently with GET request
$.get("someUrl, function(data, status){
console.log(data[0].latitude);
});
But whenever I make POST request like this
$.ajax({
url: 'someUrl',
type: 'post',
dataType: 'json',
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
data: object
});
I get the following
OPTIONS XHR "someUrl" [HTTP/1.1 403 Forbidden 4ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "someUrl".
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
How can I solve this issue?
To code to set the CORS configuration globally in main Spring Boot application is given below. Now, you can create a Spring Boot web application that runs on 8080 port and your RESTful web service application that can run on the 9090 port.
This @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.
Simple way of configuring CORS filter with Spring Boot app is to make @Component
class which implements Filter
like this:
@Component
public class SimpleCORSFilter implements Filter {
@Override
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, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Expose-Headers", "Location");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
It works great with spring-boot 1.3.0
EDIT (October 2017):
Still works with spring-boot 1.5.8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With