对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头

时间:2018-05-02 10:58:14

标签: angular spring-boot

当我尝试使用angular4作为前端上传文件并将其放入数据库时​​出现此错误

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

这是我的服务

upload(fichier) {
            return this._http.post(this._urlbase+'upload',{"file":fichier} ,       
            { headers : new HttpHeaders().set('Content-Type', 'multipart/form-data' ). append('Access-Control-Allow-Origin','*')}                
        )   .subscribe(response => {
                    this.getAllFichiers();        
                    this.snackBar.open('le fichier est bien ajouté', 'Annuler', {
                        duration: 2000,
                        });
                }, error => {
                    console.error('erreur de l\'ajout ', error);
                })
        }

这是我的component.ts

upload() {
    let fichier=this.fileInput.nativeElement.files[0];
    console.log(fichier);  
      const formdata=new FormData();
     formdata.append('file',fichier);
     console.log(formdata);
   this.fileManagerService.upload(fichier);}

对于后端我正在使用spring boot并且我添加了跨越来源以允许访问:

@CrossOrigin(exposedHeaders="Access-Control-Allow-Origin")

我尝试使用ARc作为客户端并且工作。但是当我想要角度。这似乎并不容易..可能有人帮助我 谢谢

1 个答案:

答案 0 :(得分:1)

您可以添加:@CrossOrigin(“*”)

@RestController
@RequestMapping("api")
@CrossOrigin("*")
public class Service () {
  // Code
}
相关问题