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.