Blocked by CORS : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the resource

Access to XMLHttpRequest at 'http://localhost:8080/employee/add' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am following a youtube tutorial and trying to create a Employee Manager Application. I am using Spring with Angular. I faced the CORS issue during fetching all the employees and I wrote the following code in the Main class to overcome that. I got this code from the same Youtube channel I am following.

@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);
} 

With the above code, fetching of all employees happened correctly. But when I am trying to add a new employee, it is giving the above error.

The code snippets of addEmployee service:

after button click it calls this function

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 adding new employee

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

Does anything more need to be added to the CORS configuration? Am I making mistake anywhere else?

I am very much new to both Spring and Angular.

1 answer

  • answered 2021-10-24 08:11 YogendraR

    Update your CORS config like this:

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum