Angular14 / Spring boot 2.7.3 CORS HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: '....', ok: false, …}

Viewed 26

I am working on a side project. I have shuffled the web to find the CORS solution for past couple of days and just unable to crack it. Below is the back end app

@SpringBootApplication
public class BackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedOrigins("http://localhost:4200")
                        .allowedHeaders("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .maxAge(3600);
            }
        };
    }
}

And here is what I have in Angular -

@Injectable({
  providedIn: 'root'
})
export class ConcertService {

  private baseURL = "http://localhost:8080/concerts";

  constructor(private httpClient: HttpClient) { }

  getConcertsList(): Observable<Concert[]>{
    return this.httpClient.get<Concert[]>(`${this.baseURL}`);
  }

  addConcert(concert: Concert): Observable<Object>{
    return this.httpClient.post(`${this.baseURL}`, concert);
  }  

Here is my 'add-component'

export class AddConcertComponent implements OnInit {

  concert: Concert = new Concert();
  constructor(private concertService: ConcertService, 
    private router: Router) { }

  ngOnInit(): void {
  }

  saveConcert() {
    this.concertService.addConcert(this.concert).subscribe( data => {
      console.log(data);
      this.goToConcertList();
    },
    err => console.log(err));
  }

  goToConcertList() {
    this.router.navigate(['/concerts']);
  }

  onSubmit(){
    console.log(this.concert);
    this.saveConcert();
  }

}

Edit after first responses below: GET is working fine. POST is where I am running into issues. Here is what my console shows me -

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080/concerts', ok: false, …}

Help please...

0 Answers
Related