-1

I am building a simple web app with angular and spring boot and I am totally new to both of these frameworks. I am attempting to make an http GET request with angular HttpClient but I am running into a cors error like this:

Access to XMLHttpRequest at 
'http://127.0.0.1:8080/api/employees/all' from origin 
'http://127.0.0.1:4200' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I am using angular code like this:

  this.http.get('http://127.0.0.1:8080/api/employees/all')
  .subscribe(data => {
    console.log(JSON.stringify(data));
  });

but when I started running into this error I changed it to this:

  private httpOptions = {
headers: new HttpHeaders({
  'Content-Type': 'application/json',
})
};

this.httpOptions.headers.set('Authorization', 'Basic admin:admin123');
this.httpOptions.headers.set('Access-Control-Allow-Origin', '*');
this.httpOptions.headers.set('Access-Control-Allow-Method', 'GET, PUT, POST, DELETE, OPTIONS');
this.httpOptions.headers.set('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
this.http.get('http://127.0.0.1:8080/api/employees/all')
  .subscribe(data => {
    console.log(JSON.stringify(data));
  });

However this had no effect. I found some posts with similar issues where people had solved their problem by adding the @CrossOrigin annotation to there spring java code and so I also tried this:

@CrossOrigin
@GetMapping(path = "/employees/all") // class @RequestMapping is "/api"
public @ResponseBody Iterable<Employee> getAllEmployees() {
    System.out.println("endpoint reached");
    return employeeRepository.findAll();
}

but this does not work either. I keep getting the same error. I think that I am not fully understanding where the problem is originating. Is this a server-side problem or a client-side problem? Also how can I fix this?

I appreciate any help in solving this. Thank you in advance.

mox_mox
  • 111
  • 2
  • 10
  • CORS is a server-side problem. Read an article about it, or [an answer to one of the many questions we get about it a day](https://stackoverflow.com/a/43881141/215552). – Heretic Monkey Feb 09 '20 at 22:47

2 Answers2

1

You forgot the value inside the @CrossOrigin

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

Flav Lft
  • 23
  • 6
0

It is a server side problem, the easy but non secure way it's to retrieve each API call with the Access-control-allow-origin set to *. If you really need it until the backend is fixed, you can use an extension on chrome: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=es

fabianGarga
  • 373
  • 3
  • 11