Angular Autocomplete Implementation Generates CORS Error

70 Views Asked by At

I am trying out the auto complete feature in angular and I keep running into CORS error. Other API calls work fine.

I came across this but it wasnt very useful.

Below is my implementation

ngOnInit(): void {
     const url = this.setupApiUrl + "GetBranches/";
    this._dataService.SetHeaders()
   this.branchNameCtrl.valueChanges
     .pipe(
       debounceTime(2000),        
       tap(() => {
         this._dataService.SetHeaders();
         this.errorMsg = "";
         this.branchList = [];
         this.isLoading = true;
       }),
       switchMap(value => this._dataService.GetResults<BranchViewModel>(url + value)
         .pipe(
           finalize(() => {
             this.isLoading = false
           }),
         )
       )
     )
     .subscribe(data => {
       if (data.result['Search'] === undefined) {
         this.errorMsg = data.result['Error'];
         this.branchList = [];
       } else {
         this.errorMsg = "";
         this.branchList = data.result['Search'];
        }        console.log(this.branchList);
     });
   }  
1

There are 1 best solutions below

3
Sherif Elmetainy On

It could be that the call this._dataService.SetHeaders() is using headers not allowed by your the server's CORS policy. If you are using dotnet core, you may need to call AllowAnyHeader or AllowCredentials, or may be allow a specific header.

See https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#set-the-allowed-request-headers