【发布时间】: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