问题
I am trying to connect to an Api (who is not mine), but i get CORS error (screen 1).
Then i tried to add 'Access-Control-Allow-Origin': '*' in my header but i get the same result (screen2).
Here is my code :
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}
);
}
}
I don't know what to do anymore..
Thanks
回答1:
Finally found an excellent article about my prob. It mentions i had 3 solutions :
CORS header (requires server changes) ==> Then NO
JSONP ==> heeem ... NO
Proxy Server ==> Well .. ok
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)
Then i do the folowing :
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}
);
}
}
And finaly it works.
回答2:
The 'Access-Control-Allow-Origin': '*' should be not be set in your request, but in the server's response instead. Hopefully you have access to this server.
Also consider not using the wildcard but only allowing http://localhost:4200. No need to open to everybody.
回答3:
Postman requests go through because it doesn't care about CORS. Like Chris stated, CORS should be setup in the server (keyforge).
I looked at the site and looks like they don't have any api documentation yet, so you're best bet would be to contact their developer team and ask if they can register localhost:4000 in their whitelist.
来源:https://stackoverflow.com/questions/54847782/angular-cors-request-failed