Angular CORS请求失败 [英] Angular CORS request failed
问题描述
我正在尝试连接到Api(不是我的人),但出现CORS错误(屏幕1).
I am trying to connect to an Api (who is not mine), but i get CORS error (screen 1).
然后我尝试在标题中添加'Access-Control-Allow-Origin':'*',但得到的结果相同(screen2).
Then i tried to add 'Access-Control-Allow-Origin': '*' in my header but i get the same result (screen2).
这是我的代码:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-analyzer',
templateUrl: './analyzer.component.html',
styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {
constructor(private http: HttpClient) {
this.getDeck().subscribe(res => console.log(res));
}
ngOnInit() {
}
getDeck() {
const headers = new HttpHeaders({
'Access-Control-Allow-Origin': '*'
});
return this.http.get('https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
{headers: headers}
);
}
}
我不知道该怎么办.
谢谢
推荐答案
最后找到了一个出色的文章. 它提到我有3个解决方案:
Finally found an excellent article about my prob. It mentions i had 3 solutions :
-
CORS标头(需要服务器更改)==>然后否
CORS header (requires server changes) ==> Then NO
JSONP ==> heeem ...不
JSONP ==> heeem ... NO
代理服务器==>好吧..
Proxy Server ==> Well .. ok
我尝试第三个解决方案.但老实说,我很灰心,所以首先我尝试一个不错的解决方案:我借用了cors代理(此一个很好)
I try the third solution. But to be honest i was quite discouraged, so first i try it with a nice solution : i borrow a cors proxy (this one is quite good)
然后我进行以下操作:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-analyzer',
templateUrl: './analyzer.component.html',
styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {
res;
constructor(private http: HttpClient) {
this.getDeck().subscribe(res => {console.log(res); this.res = res; });
}
ngOnInit() {
}
getDeck() {
const headers = new HttpHeaders({
'X-Requested-With': 'XMLHttpRequest'
});
return this.http.get('https://cors-anywhere.herokuapp.com/https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
{headers: headers}
);
}
}
最终它可以正常工作.
这篇关于Angular CORS请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!