所以我目前正在学习如何制作API请求和Angular 6,我得到了Yelp Fusion Api的HTTP Get请求,但是我不太明白我从一个类似的例子在网上复制工作的一行。
private configUrl: string = "https://corsanywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?location=boston&term=steak";
constructor(private http: HttpClient) {}
sendHttpRequest() {
const headers = new HttpHeaders().set("Authorization", "Bearer MyApiKey");
return this.http.get<JSON>(this.configUrl, {
headers
});
}
如果我删除yelp GET URL前面的“https://corsanywhere.herokuapp.com/”,它不起作用,我在控制台中收到此错误。为什么是这样?对不起,我是新来的。
OPTIONS https://api.yelp.com/v3/businesses/search?location=boston&term=steak 403 ()
Failed to load https://api.yelp.com/v3/businesses/search?location=boston&term=steak: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
这是您通常会得到的典型CORS问题。 CORS是一种基于浏览器的策略,不允许跨源资源共享。允许它:
URL的前一部分(https://corsanywhere.herokuapp.com/
)似乎就是这样做的。它基本上充当Angular App和Yelp API之间的代理(案例2)。
由于CORS是基于浏览器的策略,并且您通过充当代理的corsanywhere
访问YELP API,因此您没有遇到CORS问题。