[英]Angular CORS request failed
我試圖連接到Api( 不是我的 ),但出現CORS錯誤(屏幕1)。
然后我嘗試在標題中添加“ Access-Control-Allow-Origin”:'*',但得到的結果相同(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個解決方案:
CORS標頭(需要服務器更改)==>然后,否
JSONP ==> heeem ...否
代理服務器==>好吧..好的
我嘗試第三個解決方案。 但說實話我很沮喪,所以我第一次嘗試用一個很好的解決方案:我借用CORS代理(這一個相當不錯)
然后我做下面的事情:
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}
);
}
}
最后,它的工作原理。
'Access-Control-Allow-Origin':'*'不應在您的請求中設置,而應在服務器的響應中設置。 希望您可以訪問此服務器。
還可以考慮不使用通配符,而只允許使用http:// localhost:4200 。 無需向所有人開放。
郵遞員的請求得到處理是因為它不關心CORS。 就像克里斯說的那樣,應該在服務器(keyforge)中設置CORS。
我查看了該網站,看起來他們還沒有任何api文檔,因此,最好的辦法是與他們的開發人員團隊聯系,並詢問他們是否可以在其白名單中注冊localhost:4000。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.