Все еще получаю ошибку cors после добавления аннотации @CrossOriginJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Все еще получаю ошибку cors после добавления аннотации @CrossOrigin

Сообщение Anonymous »

У меня возникли проблемы с ошибкой CORS.
Я пытаюсь опубликовать файл в базе данных, но использую другую конечную точку в том же серверном приложении, где я отправляю другие данные из другой конечной точки. Вот ошибка:

Отсутствует разрешение CORS

Вот внутренний контроллер для первая конечная точка:

Код: Выделить всё

@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 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

}
Вот контроллер для другой конечной точки:

Код: Выделить всё

@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

}
Вот мой компонент загрузки файла в 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
Пользовательский компонент загрузки:

Код: Выделить всё

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
мои услуги, для публикации пользователя:

Код: Выделить всё

public postUsers(user_name: string, password: string, name: string, surname: string, birth: Date, eMail: string): Observable{
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(url, body, httpOtions)
.pipe(catchError(this.handleError));
}
способ публикации файла:

Код: Выделить всё

  public postFile(formData: FormData): Observable{
const url = `http://localhost:8080/api/v1/file/`;
return this.http.post(url+`/Upload`, formData);
Из Почтальона всё работает. Я подозреваю, что проблема в двух разных аннотациях @CrossOrigin, содержащих один и тот же URL-адрес.
Что я делаю не так?
Можете ли вы мне помочь?
Если вам нужен другой кусок кода, спросите, и я его опубликую.

Подробнее здесь: https://stackoverflow.com/questions/791 ... annotation
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»