kodazys
kodazys

Reputation: 149

CORS error connecting Angular to Spring (localhost 8080 <--> localhost 4200)

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?

Upvotes: 1

Views: 2273

Answers (2)

Sebastian
Sebastian

Reputation: 6057

I've annotated my Controller with

@CrossOrigin(origins = "http://localhost:4200")

and it works.

Upvotes: 0

MenyChiko
MenyChiko

Reputation: 21

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

Upvotes: 1

Related Questions