Thursday, June 21, 2018

No 'Access-Control-Allow-Origin' header is present on the requested resource.

In this blog I'm try to explain the way we can solve above issue from the "SpringBoot" side.

I faced the below issue with calling my service through the React.
Failed to load http://xx.xx.xx.xx:8080/api/yy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.xx.xx.xx:3000' is therefore not allowed access.

Default, it didn't set the "Access-Control-Allow-Origin" header. So, you can solve this as below.

1. Create a filter as below
 
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter extends GenericFilterBean implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        //httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        //httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        //httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
        //httpResponse.setHeader("Access-Control-Max-Age", "3600");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

Add if you need add more headers you can add as above.

2. In the main application you have to set the @Bean as below
@SpringBootApplication
@EnableMongoRepositories(basePackages= {"com.home"})
@EntityScan(basePackages = {"com.home"})
@EnableEurekaClient
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
        registrationBean.setName("CORS Filter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }
}


After this, when you execute the service you can see the 'Access-Control-Allow-Origin' in the header.

Enjoy...!!!