Angular 6 Yelp Fusion API GET请求

时间:2018-09-19 03:52:57

标签: angular api http get yelp

因此,我目前正在学习如何发出API请求和Angular 6,并且我将我的HTTP Get请求发送到Yelp Fusion Api可以正常工作,但是我不太理解我从类似示例在线复制的那一行可以工作。

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.

1 个答案:

答案 0 :(得分:0)

这是您通常会收到的典型CORS问题。 CORS是基于基于浏览器的的策略,不允许跨源资源共享。要允许它:

  1. 请求域应该在API端列入白名单。
  2. 或者应该通过代理服务器访问请求的API。
  3. 或者还有其他几种可以解决的方法,超出了此答案的范围。

URL(https://corsanywhere.herokuapp.com/)的上一段似乎就是这样做的。它基本上是Angular应用程序和Yelp API(案例2 )之间的代理。

由于CORS是基于浏览器的策略,并且您通过充当代理的corsanywhere来访问YELP API,所以不会遇到CORS问题。