【发布时间】:2021-06-13 13:03:29
【问题描述】:
我在 Spring Boot 和 Angular 中开发的 API 存在问题。当我尝试用图像录制新的表演时,我总是有与 Cors 跨源标题相关联的相同错误。
这是我的控制器和用于创建 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);
}
}
这是我的角度服务
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'))
);
}
这是我的角度方法 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')
}
});
}
我还是有同样的错误
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
【问题讨论】:
-
我认为您不应该将 'Acces-Control-Allow-Origin': '/*' 传递到 POST 中,但这可能不是主要问题。
-
是的,迈克尔,你是对的,我绝望地说,希望它能奏效。
标签: angular spring-boot