我遇到了 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<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
}
这是另一个端点的控制器:
@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<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));
}
文件发布方式:
public postFile(formData: FormData): Observable<any>{
const url = `http://localhost:8080/api/v1/file/`;
return this.http.post(url+`/Upload`, formData);
}
邮递员一切正常。我怀疑问题是两个不同的
@CrossOrigin
注释包含相同的 URL。
我做错了什么?
你能帮我吗?
如果您需要其他代码,请询问,我会发布它。
如果问题是从前端端点和端口无法从后端获得任何结果或数据,那么我认为可以通过将此代码添加到后端应用程序文件 java->com| 来解决此问题。
|应用
|控制器
|实体
|DTO
|应用程序.java
这是代码=>
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:54390/"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
不要忘记这个注解@Bean