被 CORS 阻止:对预检请求的响应未通过访问控制检查:资源上不存在"访问控制-允许源"标头



从原点'http://localhost:4200'访问'http://localhost:8080/employee/add'的XMLHttpRequest已被CORS策略阻止:对预飞行请求的响应未通过访问控制检查:请求的资源上不存在'Access- control - allow - origin '标头。

我正在遵循一个youtube教程,并试图创建一个员工经理应用程序。我正在使用Spring和Angular。我在获取所有员工时遇到了CORS问题,我在Main类中编写了以下代码来克服这个问题。我从我关注的同一个Youtube频道得到了这个代码。

@Bean
public CorsFilter corsFilter(){


CorsConfiguration corsConfiguration= new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200" ));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin","Access-Control-Allow-Origin","Content-type","Accept","Authorization",
"Access-Control-Allow-Origin: *","Access-Control-Allow-Methods: GET, DELETE, HEAD, OPTIONS","Origin", "Accept","X-Reuested-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-Credentials"));
UrlBasedCorsConfigurationSource urlBasedCosConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCosConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter((CorsConfigurationSource) urlBasedCosConfigurationSource);
} 

通过上面的代码,所有员工的抓取都正确地进行了。但是当我试图添加一个新员工时,它给出了上面的错误。

addemployservice的代码片段:

点击按钮后调用这个函数

add-employee-component.ts

onAddEmployee(addForm : NgForm) : void{
this.employeeService.addEmployee(addForm.value).subscribe(
(response: Employee) => {
console.log(response);
},
(error:HttpErrorResponse) => {
alert(error.message);
}
)
}

employee.service.ts

public addEmployee(employee : Employee) : Observable<Employee>{
console.log(`${this.apiServerUrl}/employee/add`);
return this.http.post<Employee>(`${this.apiServerUrl}/employee/add`,employee);
}

spring service for add new employee

@PostMapping("/add")

public ResponseEntity<Employee> addNewEmployee(@RequestBody Employee employee){
Employee newEmployee = empService.addEmployee(employee);
return new ResponseEntity<>(newEmployee,HttpStatus.OK);
}

是否需要在CORS配置中添加更多内容?我在别的地方出错了吗?

我对Spring和Angular都是新手。

像这样更新CORS配置:

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
configuration.setAllowCredentials(true);
configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "OPTIONS", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Content-Type", "Authorization", "Origin",
"Accept", "Access-Control-Request-Method", "Access-Control-Request-Headers"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

相关内容

  • 没有找到相关文章

最新更新