【问题标题】:Angular Autocomplete Implementation Generates CORS ErrorAngular 自动完成实现生成 CORS 错误
【发布时间】:2021-08-15 12:46:33
【问题描述】:

我正在尝试 Angular 的自动完成功能,但我一直遇到 CORS 错误。 其他 API 调用工作正常。

我遇到了this,但它不是很有用。

下面是我的实现

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

【问题讨论】:

    标签: angular typescript autocomplete angular-material .net-core-angular


    【解决方案1】:

    可能是调用 this._dataService.SetHeaders() 使用了服务器 CORS 策略不允许的标头。如果您使用的是 dotnet core,您可能需要调用 AllowAnyHeader 或 AllowCredentials,或者可能允许特定的标头。

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

    【讨论】:

    • 是的,但我确实有其他使用相同标头的 API 调用工作正常
    • if (adminApiConfiguration.CorsAllowAnyOrigin) { builder.AllowAnyOrigin(); } "CorsAllowAnyOrigin": true,
    • public SetHeaders(page?: number, itemsPerPage?: number) { const tokenValue = "Bearer " + this._securityService.getToken(); this.headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': tokenValue, 'Pagination': page + "," + itemsPerPage }); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2015-10-07
    • 2018-08-17
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多