Search code examples
springspring-bootcorsfetchopera

Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error


I'm building a Spring Boot application with Spring Security. I have a delete functionality which is done through AJAX request using JavaScript's Fetch API. The functionality works correctly in Chrome and Firefox, however it causes problem in Opera. As I mentioned, 'No 'Access-Control-Allow-Origin' header is present on the requested resource' error is shown in the console.

I searched for it, it was because of CORS, browsers normally doesn't allow AJAX requests to different origins, however delete request is in the same domain and if it does work in Chrome/Firefox, I wonder why it doesn't in Opera.

Now, I'm not sharing any code related to application, just because if there was a problem in core, it wouldn't work in other browsers, would it? But in case any code should be shared, please say it, so I'll share. But right now, I don't even know what is wrong. Thanks beforehand.


Solution

  • You can allow your all header by implementing Filter.

    Try with this:

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class CORSFilter implements Filter {
    
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest request = (HttpServletRequest) req;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            //response.setHeader("Access-Control-Expose-Headers","yourCustomHeaderIfExist");
    
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, res);
            }
        }
    
        @Override
        public void init(FilterConfig filterConfig) {
        }
    
        @Override
        public void destroy() {
        }
    
    }
    

    And add @CrossOrigin annotation before your controller.

    You can also try with add this bean:

     @Bean
            public WebMvcConfigurer corsConfigurer() {
                return new WebMvcConfigurerAdapter() {
                    @Override
                    public void addCorsMappings(CorsRegistry registry) {
                        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");
    
    
                    }
                };
            }