【问题标题】:HttpClient API Call in Angular keeps failingAngular中的HttpClient API调用不断失败
【发布时间】:2021-07-07 02:57:40
【问题描述】:

我正在尝试在 Angular 中调用需要授权的 API。我的代码可以编译,但数据不显示,并且在开发人员工具中我收到一条错误消息,指出我的访问已被 CORS 策略阻止,并且没有访问控制允许来源。我一直在使用 CORS Chrome 扩展来启用 CORS。 我在下面提供了我一直在使用的代码,我对 Angular 很陌生,所以它很简单,但我不知道是否有办法解决这个问题并让 API 调用正常工作?我也无权访问服务器端代码,因此我无法在该端添加任何 CORS 代码。

app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My Title';

data: any = {};

constructor(private http: HttpClient) {}

ngOnInit() {

const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer my-auth-token'
}),
};
this.http.get('https://mygateway.com', httpOptions).subscribe((data)=>{
console.log(data)
});
}

任何帮助将不胜感激:)

【问题讨论】:

  • 1.尝试在运行 ng serve 时使用 --disable-host-check 2. 在后面为所有可用方法添加选项请求 3. 在 chrome://flags 中查看浏览器设置

标签: angular cors authorization httpclient


【解决方案1】:

你应该实现一个代理文件配置来解决这个问题。

【讨论】:

    【解决方案2】:

    最好通过代理.. 正如这里的#1 答案所示: How to add CORS request in header in Angular 5

    {
        "/api": {
          "target": "https://mygateway.com",
          "secure": true,
          "changeOrigin": true,
          "pathRewrite": {
            "^/api": ""
          }
        }
      }
    

    那么你的电话会变成这样:

    this.http.get('/api', httpOptions).subscribe((data)=>{
    console.log(data)
    });
    
    

    此处的其他信息: https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85

    在顶部的 SO 链接中还列举了其他选项,例如使用 fetch。

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 2022-06-28
      • 1970-01-01
      • 2018-05-08
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多