I have a problem with my API which I developed in Spring boot and Angular. when I try to record a new performance with an image I always have the same error linked to the Cors cross origin headers.
Here is my controller and the method used to create a Prestation
@RestController
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RequestMapping("/prestations")
public class PrestationController {
private byte[] bytes;
@Autowired
IPrestationService prestationService;
@Autowired
PrestationRepository prestationRepository;
@Autowired
ServletContext context;
@PostMapping
public ResponseEntity<MessageResponse> savePrestaWithImage(@RequestParam("file") MultipartFile file, @RequestParam("prestation")String prestation)
throws JsonParseException, JsonMappingException, Exception {
Prestation presta = new ObjectMapper().readValue(prestation, Prestation.class);
boolean isExist = new File(context.getRealPath("/Images/")).exists();
if(!isExist){
new File(context.getRealPath("/Images/")).mkdir();
System.out.println("dossier créer");
}
String filename = file.getOriginalFilename(); // je recupere le nom de l'image
String newFileName = FilenameUtils.getBaseName(filename)+"."+FilenameUtils.getExtension(filename);
File serverFile = new File(context.getRealPath("/Images/"+File.separator+newFileName));
try {
System.out.println("Image");
FileUtils.writeByteArrayToFile(serverFile, file.getBytes());
}catch (Exception e){
e.printStackTrace();
}
presta.setPhoto(newFileName);
Prestation prestation1 = prestationRepository.save(presta);
if(prestation1 != null){
return new ResponseEntity<MessageResponse>(new MessageResponse(""), HttpStatus.OK);
}else {
return new ResponseEntity<MessageResponse>(new MessageResponse("Prestation not saved"), HttpStatus.BAD_REQUEST);
}
}
Here is my angular service
savePrestation(prestation: Prestation): Observable<Prestation> {
const httpOptions = {
headers: new HttpHeaders({
'Content-type ': 'application/json',
'Acces-Control-Allow-Origin': '/*'
})
}
return this.http.post<Prestation>(this.SAVE_PRESTA, prestation, httpOptions).pipe(
tap(_ => this.log(`save prestation with id = ${prestation.id}`)),
catchError(this.handleError<any>('addPresta'))
);
}
here is my angular method savePresta
savePresta() {
const uploadData = new FormData();
uploadData.append('imageFile', this.selectedFile, this.selectedFile.name);
this.selectedFile.imageName = this.selectedFile.name;
this.http.post(this.SAVE_PRESTA + '/upload', uploadData, { observe: 'response' }).subscribe(
(response) => {
if (response.status == 200) {
this.service.savePrestation(this.prestation).subscribe(
(prestation) => {
this.prestation = prestation;
this.goBack();
});
console.log('image uploaded successfull');
} else {
console.log('image not uploaded sucessfull')
}
});
}
I still have the same error
Access to XMLHttpRequest at 'http://localhost:8080/prestations' 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.
POST http://localhost:8080/prestations net::ERR_FAILED
ERROR HttpErrorResponse headers: HttpHeaders status: 0 statusText: "Unknown Error" url:"http://localhost:8080/prestations", ok: false …
help me please that days that I block the top I tried everything but nothing helped