Angular - 通过 http 连接到 API 时出现问题(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)

问题描述 投票:0回答:1

我正在尝试使用http(角度)从API获取数据。如果我通过

ngOnInit
调用该函数,数据将正确下载:

handleError(error: HttpErrorResponse) {
    return throwError(() => new Error('Something bad happened; please try again later.'));
}

header4 = new HttpHeaders({
  'x-api-key': this.key,
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'GET',
  'Access-Control-Allow-Origin': '*'
});

listaProduktow: any = [];  

getProducts() {
  this.http.get(this.productUrl + "?resultsLimit=2", { headers: this.header4 })
  .pipe(catchError(this.handleError))
  .subscribe(data => {
     this.listaProduktow = data;
     console.log(data);
   });
  console.log('products loaded');
}
ngOnInit(): void {
  console.log('working!');
  this.getProducts();
}

但是,如果我想通过事件(单击按钮)使用该功能:

<button (click)="getProducts()">Szukaj</button>

它抛出一个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxx.yourtechnicaldomain.com/api/admin/v3/products/descriptions?type=id&ids=10. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

我正在使用:
角度 CLI:17.2.0
节点:21.6.0(不支持)
包管理器:npm 10.3.0

我尝试使用服务,直接从服务器运行apk...来自Google的大多数建议也没有帮助。 我不是高级 Angular 用户 - 也许这是配置问题?

angular http cors
1个回答
0
投票

在前端添加此类标头通常不起作用。您需要在服务器上允许您的来源。它在

ngOnInit
中工作的原因可能是因为
getProducts()
作为 Angular 组件初始化过程的一部分执行。此时,浏览器可能不会严格执行 CORS 限制,因为它被视为初始页面加载的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.