During the development of your application it is a good practice to work with 2 separate server. A server for your backend and a server for your frontend. Your JavaScript frontend will communicate with your backend to collect information using REST services.

At this moment you will incur in a problem : for security reasons browsers don’t allow that a page answering from the domainA load resources from a domainB.

You can read the detailed explanation of the CORS mechanism here: Mozilla

How to allow CORS requests


In our Angular request we have to add the header X-Requested-With. This header enables a webpage to update just partially.

this.headers = new Headers({ 'Content-Type': 'application/json' })
this.headers.append('Accept', 'application/json, text/csv');
this.headers.append('X-Requested-With', 'XMLHttpRequest');

Java EE


The filter solution can be used in Servlet compatible Servers.

class CorsFilter 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, PUT, GET, OPTIONS,  DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type, x-requested-with");
        response.setHeader("Access-Control-Max-Age", "3600");

        if (((HttpServletRequest)req).getMethod().equals("OPTIONS")) {
        } else {
            chain.doFilter(req, res);

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

Spring Boot

This solution contains Spring specific annotations. You have to update the ALLOWED_ORIGINS constant with the URL of the frontend server sending the requests to the backend server. 

public class CorsConfig {

    private static final String[] ALLOWED_ORIGINS = {"http://localhost:3000",

    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            public void addCorsMappings(CorsRegistry registry) {