-2

I have a @RestController in my java spring backend:

@GetMapping(value = "/getItems")
public List<Item> getItems()
{
    System.out.println("Requested!");
    return itemRepository.findAll();
}

I am trying to retreive the items in my Angular frontend but get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/api/getItems' 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.

But I am not sure why, because I am adding the correct header in Angular:

getItems() {
this.http.get('http://localhost:8080/api/getItems',
  {headers: new HttpHeaders({
      'Access-Control-Allow-Origin': 'http://localhost:4200',
      'Access-Control-Allow-Methods': 'GET, POST, PUT',
      'Access-Control-Allow-Headers': 'Content-Type'
    }
  )})
  .subscribe(
  data => {console.log(data);
  });
}

The get request does work in Postman, but I know that the browser is what is causing the problem, and requires that the 'Access-Control-Allow-Origin' header to be present, which I added. It compiles, but it seems like it's not adding the headers correctly. Does anyone know what's going on here?

MinhazMurks
  • 191
  • 1
  • 2
  • 13

1 Answers1

0

Oh it seems like I can add a @CrossOrigins annotation in my RestController and specify an origin in the backend!

MinhazMurks
  • 191
  • 1
  • 2
  • 13