I've encountered a strange issue with my application. The architecture of my app is as follows: ts (Angular) -> Java (Spring). I was making some GET requests from Angular to Java, as well as DELETE requests without any problems. However, when I tried to add a POST request, things got complicated. My app uses HTTP basic authentication. Here is some code from my data service:
getCurrentCars(id:number){
const headers = new HttpHeaders({ 'Content-Type':'application/json',
'Authorization': 'Basic ' + btoa(sessionStorage.getItem('username') + ':' + sessionStorage.getItem('password')) });
return this.http.get("http://localhost:8080/api/cars/getcurrentcars/"+id.toString(),{headers});
}
postNewRepair(name:string, description:string, date:string, idCar:number){
const headers = new HttpHeaders({ 'Content-Type':'application/json',
'Authorization': 'Basic ' + btoa(sessionStorage.getItem('username') + ':' + sessionStorage.getItem('password')) });
let newrepair:Repair= {name: name, date:date, description:description, idCar:idCar}
this.http.post("localhost:8080/api/repairs/postRepair",newrepair,{headers}).subscribe(resp => console.log(resp));
}
The GET request works fine, but the POST request doesn't work. Interestingly, the POST request works perfectly fine in Postman.
I have also tried to disable CORS policies, here are some examples:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/api/repairs")
public class ControllerRepair {
@RequestMapping(method = RequestMethod.POST, value = "/postRepair")
public void postRepair(@RequestParam String name, @RequestParam String date, @RequestParam String description, @RequestParam Long idCar){
LocalDate date1 = LocalDate.parse(date);
System.out.println("aaa");
iRepairService.postRepair(name, date1, description, idCar);
}
}
Here is a snippet from the HTTP configuration:
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/repairshops/**").hasAuthority("REPAIR_SHOP")
.antMatchers("/api/clients/**").hasAnyAuthority("CLIENT","REPAIR_SHOP")
.antMatchers("/login/**").fullyAuthenticated()
.anyRequest()
.authenticated()
.and()
.httpBasic();
I even attempted using a CORS configuration class I found on StackOverflow, but it not only failed to solve the issue with the POST request but also disrupted my other GET and DELETE requests.
Access to XMLHttpRequest at 'localhost:8080/api/repairs/postRepair' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Could it be that I'm missing some headers in my HTTP POST request to make it work?