Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot and CORS

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?

like image 678
nurgasemetey Avatar asked Jan 27 '16 10:01

nurgasemetey


People also ask

How do spring boots handle CORS?

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.

What is spring boot CORS?

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.


1 Answers

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

like image 112
Ivan Aracki Avatar answered Oct 01 '22 18:10

Ivan Aracki