0
votes

I am trying to connect my Frontend in Angular 8 to my backend written in Java using Spring.

My Spring backend is running on Tomcat server at localhost:8080 and Angular is open on localhost:4200. When I try to register a user (or do anything), I get this error:

Access to XMLHttpRequest at 'http://localhost:8080/Revvit/users' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In my UserController class within Spring, I've annotated the controller with

@CrossOrigin(origins= "*", allowedHeaders="*")
@Controller
public class UserController {............

However, I still get the same message in my console as noted above.

So, I'm assuming that I have to add some header allowing CORS within my Angular project, but WHERE, and HOW would I incorporate this?

1
I think this link could be useful spring.io/guides/gs/rest-service-corsHonarkhah
Cross origin * is not allowed if you have stateful request!Honarkhah
You should try to add "@CrossOrigin" with no parameters to your controller, and then activate the "org.apache.http.headers" logging category in your log4j or logback conf at DEBUG level to see what is happening (is the expected response header present ?).Tristan

1 Answers

1
votes

You can solve it by adding proxy.conf file to your project as in Angular docs: https://angular.io/guide/build#proxying-to-a-backend-server

with the proxy.conf file you can set specific end points you use in your app to a different target, for example:

{
  "/Revvit": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

then you can fetch with the HttpClient service:

this.http.get('Revvit/users')

and get the expected behavior