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.
As when you are running angular and web api, but these are running on two port. You need to enable CORS policy on your server.
If you are using web api, then enable cors policy on your project and it will solve your issue.
was full on nightmare with the cors the other day so I switched my programming paradigm.
for my web app im developing, eventually im deploying to a production, in this case Im using
Heroku
you could useGCP
or similar. To work on server side stuff like http I usePostman
to test all the http routes, postman doesn't get blocked from cors. it also can rapidly send them in an organized folder as opposed to filling out an entire use case just to get to the HTTP req.After my unit tests are done and verified I deploy server to Heroku and then I work on the client. this way the client makes requests to the server which is Elsweyr and does not receive cors.
In
startup.cs
class, add the following statements in the two methodsConfigureServices
andConfigure()
. This solution worked with me without the need to install CORS on web browsers: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
}
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.