Cross Origin Resource Sharing (CORS) in Angular or Angular 6. Problem while you make cross domain calls on localhost with different ports
angular, angular6, cors, cross-domain, spring-boot
Solution
To Solve the above problem
First you need to share the Spring boot resource for the port 4200. Annotate the class or method with @CrossOrigin(origins = "http://localhost:4200") of resource you want to share.
Yo have to configure proxy in angular application. So create a proxy.json file in angular root application. and the content goes below
{
"/api/*": {
"target": "http://localhost:8080",
"secure": "false",
"logLevel": "debug",
"changeOrigin": true
}
}
And then run `ng serve --proxy-config proxy.json` this command it will compile the code. You should see something like this on a console.
building modules 3/3 modules 0 active[HPM] Proxy created: /api ->
http://localhost:8080 Subscribed to http-proxy events: [ 'error', 'close' ]
Problem
I have come across a situation where I make a call from my angular 6 application to my spring boot application. When I call an HTTP post method in angular to the application running on a different port it throws an exception. Access to XMLHttpRequest at 'http://localhost:8080/api' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. My Angular application Running on 'http://localhost:4200' port number:4200 My Spring Boot application running on 'http://localhost:8080/api': port number:8080. There is no direct answer to solve this problem. There are few hacks to disable the security in chrome and using NGINX you can resolve this issue.