When we choose to follow any Angular and Spring Boot startup tutorials we end up with applications running on http://localhost:4200 and http://localhost:8080. Communication between the two can run into Cross-Origin Resource Sharing (CORS) blocking.

Take a look at the getting started pages for Spring Boot and Angular.

CORS error

We explore two different ways to deal with these problems in your development environment:

  • Setup nginx reverse proxy
  • Use Angular CLI proxy configuration

Setup nginx revers proxy

This would reflect how most production environments resolve this problem. We can download nginx from here.

Now configure your nginx by pasting the following in <nginx folder>/conf/nginx.conf:

worker_processes  1;
 
events {
    worker_connections  1024;
}
 
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
 
    server {
        listen       7000;
        server_name  localhost;
 
        location /OGD-opgave {
            proxy_pass http://127.0.0.1:8080;
        }
        location /api {
            proxy_pass http://127.0.0.1:8090;
        }
        location / {
            proxy_pass http://127.0.0.1:4200;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
        }
         
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

Now run <nginx folder>/nginx.exe and both applications are reachable at port 7000!

Use Angular CLI proxy configuration

We can also utilize the proxy configuration of the Angular CLI. By putting a file named proxy.conf.json in the root of your Angular application with the following content:

{
    “/<application path>”: {
        “target”: “http://localhost:8080/”,
        “secure”: false,
        “changeOrigin”: true,
        “logLevel”: “debug”,
        “pathRewrite:”: {
            “^/<application path>”: “”
        }
    }
}

Now we need to run the application with this configuration with this command:  ng serve --proxy-config proxy.conf.json . Or automate this by adding it as a script in your package.json.

These two strategies will keep you right on going when using Spring Boot as a back-end for your Angular application.