Still getting cors error after adding @CrossOrigin annotation

Discussão em 'Angular' iniciado por marcom966, Outubro 22, 2024.

  1. marcom966

    marcom966 Guest

    I'm having troubles with the CORS error. I'm trying to post a file to the database but using another endpoint in the same backend application where I post other data from another endpoint. Here's the error:


    CORS Missing Allow Origin
    ​

    Here's the backend controller for the first endpoint:

    @RestController
    @RequestMapping(path="api/v1/file")
    @CrossOrigin(origins = "http://localhost:4200")
    public class filecontroller {
    @Autowired
    private final FileSystemStorageService filesService;

    public filecontroller(FileSystemStorageService filesService) {
    this.filesService = filesService;
    }



    @PostMapping("/upload")
    public ResponseEntity<responseMessage> uploadFiles(@RequestParam MultipartFile file){
    String message = "";
    try{
    filesService.store(file);
    message = "File Uploaded successfully: "+file.getOriginalFilename();
    return ResponseEntity.status(HttpStatus.OK).body(new responseMessage(message));
    }catch (Exception e){
    message = "Could not upload the file: "+file.getOriginalFilename() + "!";
    return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new responseMessage(message));
    }
    }

    //other methods



    }


    Here's the controller for the other endpoint:

    @RestController
    @RequestMapping(value = "api/v1/user")
    @CrossOrigin(origins = "http://localhost:4200")
    public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
    this.userService = userService;
    }


    //other methods


    @PostMapping
    public void registerNewUser(@RequestBody UserClass user){
    userService.addNewUser(user);
    }
    //other methods



    }


    Here's my upload file component in Angular:

    constructor(private route: Router, private files: PostFileServiceService) { }

    public main(){
    this.username = localStorage.getItem('user_name');
    }
    public onChangeFile(event: any){
    this.formData = new FormData();
    this.file = event.target.files[0];
    if(this.file){
    this.name = this.file.name;
    this.size = this.file.size;
    this.type = this.file.type;
    this.formData.append('fileSize', this.size);
    this.formData.append('fileType', this.type);
    this.userName = this.username;
    this.formData.append('userName', new Blob([JSON.stringify(this.userName)], {type: 'multipart/form-data'}));
    this.nameOfficial = this.name;
    if(this.nameOfficial.includes(" ")){
    this.nameConcat = this.nameOfficial.split(" ").join("");
    }
    this.formData.append('fileName', this.nameConcat ? this.nameConcat : this.nameOfficial);
    }else if(this.file==null){
    return
    }
    }
    public onSubmit(){
    this.requestSub = this.files.postFile(this.formData).subscribe((resp)=>{
    if(resp==null){
    this.subscribed = true;
    this.toCongrats('fileSuccessfull');
    }
    })
    }
    //other methods


    The uploading user component:

    public onSubmit(form: NgForm){
    this.name = form.value.FullName;
    this.surname = form.value.Surname;
    this.birthday = form.value.birthday;
    this.email = form.value.eMail;
    this.nickname = form.value.Nickname;
    this.password = form.value.Password;
    this.pasDue = form.value.passwordDue;
    if(this.pasDue!=this.password){
    this.samePassword=true;
    }
    let user_name = this.nickname;
    if(!user_name){
    this.notNickname=true;
    }
    let birth = this.birthday;
    if(!moment(birth).isValid()){
    this.wrongDate=true;
    }
    let eMail = this.email;
    if(!eMail.includes('@')){
    this.fakeEmail=true;
    return
    }
    let name = this.name;
    let surname = this.surname;
    let password = this.password;
    if(!password){
    this.notPassword=true;
    }
    this.requestSub = this.fetchUsers.postUsers(user_name, password, name, surname, birth, eMail)
    .pipe(catchError(err=>{
    return throwError(()=>{
    let error = new Error(err).message.toString();
    if(error.includes('500')){
    this.emailAlreadyExist=true;
    }
    });
    }))
    .subscribe((resp)=>{
    if(resp==null){
    this.Destination('subscribed');
    }
    })
    }
    //other methods


    my services, for posting the user:

    public postUsers(user_name: string, password: string, name: string, surname: string, birth: Date, eMail: string): Observable<any>{
    const body = JSON.stringify({ user_name, password, name, surname, birth, eMail })
    const httpOtions ={
    headers: new HttpHeaders({
    "Content-Type":"application/json",
    })
    };
    const url = `http://localhost:8080/api/v1/user?user_name=${user_name}&password=${password}&name=${name}&surname=${surname}&birth=${birth}&eMail=${eMail}`;
    return this.http.post<any>(url, body, httpOtions)
    .pipe(catchError(this.handleError));
    }


    the file posting method:

    public postFile(formData: FormData): Observable<any>{
    const url = `http://localhost:8080/api/v1/file/`;
    return this.http.post(url+`/Upload`, formData);


    }

    From Postman everything works. I suspect the problem is the two different @CrossOrigin annotations that contains the same URL. What am I doing wrong? Can you please help me? If you need some other piece of code please ask and I'll post it.

    Continue reading...

Compartilhe esta Página