Angular2 Yelp API CORS错误 [英] Angular2 Yelp API CORS error

查看:521
本文介绍了Angular2 Yelp API CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现V3 API时,我面对Ionic2 / Angular2应用程序的以下CORS问题:

While implementing the V3 API I face the following CORS problem with my Ionic2/Angular2 application:

XMLHttpRequest无法加载 https://api.yelp.com/v3/businesses/search 。对预检请求的响应不通过访问控制检查:在请求的资源上不存在Access-Control-Allow-Origin头。原因 http:// localhost:8100 因此不允许访问。该响应具有HTTP状态代码404.

XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search. 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:8100' is therefore not allowed access. The response had HTTP status code 404.

在使用API​​的V2时,我使用http.jsonp不再适用了绕过CORS问题,因为授权承载应该添加在GET请求的头部(据我所知,Jsonp头部不能被修改)。

While using the V2 of the API, I was "bypassing" the CORS problem using http.jsonp whish isn't applicable anymore, because the authorization bearer should be added in the header of the GET request (as far as I understood, a Jsonp header can't be modified).

这是为什么我试过

private queryYelp(yelpOAuth:YelpCommunication.YelpOAuthSignature, nextTo:AddressLocation.Location):Promise<{}> {

    let params:URLSearchParams = new URLSearchParams();

    params.set('limit', '' + Resources.Constants.Default.YELP.LIMIT);
    params.set('latitude', '' + nextTo.coordinates[0]);
    params.set('longitude', '' + nextTo.coordinates[1]);
    params.set('radius', '' + Resources.Constants.Default.YELP.RADIUS);
    params.set('sort_by', Resources.Constants.Default.YELP.SORT.BEST_MATCHED);

    let headers:Headers = new Headers();
    headers.append('Authorization', 'Bearer ' + yelpOAuth.access_token);
    let options:RequestOptions = new RequestOptions({
        headers: headers,
        search: params,
        withCredentials: true
    });

    return new Promise((resolve, reject) => {
        this.http.get(Resources.Constants.Default.YELP.URL, options)
            .map(res => res.json())
            .subscribe((businesses:Yelp.YelpBusiness[]) => {
                resolve(businesses);
            }, (errorResponse:Response) => {
                reject(errorResponse);
            });
    });
}

private queryYelp(yelpOAuth:YelpCommunication.YelpOAuthSignature, nextTo:AddressLocation.Location):Promise<{}> {
    return new Promise((resolve, reject) => {
        let xhr:XMLHttpRequest = new XMLHttpRequest();

        let formData:FormData = new FormData();
        formData.append('limit', '' + Resources.Constants.Default.YELP.LIMIT);
        formData.append('latitude', '' + nextTo.coordinates[0]);
        formData.append('longitude', '' + nextTo.coordinates[1]);
        formData.append('radius', '' + Resources.Constants.Default.YELP.RADIUS);
        formData.append('sort_by', Resources.Constants.Default.YELP.SORT.BEST_MATCHED);

        xhr.onload = () => {
            console.log("status " + xhr.status);
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status == 201) {
                let businesses:Yelp.YelpBusiness[] = JSON.parse(xhr.responseText);
                resolve(businesses);
            } else {
                reject();
            }
        };

        xhr.onerror = () => {
            alert('Woops, there was an error making the request.');
        };

        xhr.open("GET", Resources.Constants.Default.YELP.URL, true);
        xhr.setRequestHeader("Authorization", 'Bearer ' + yelpOAuth.access_token);
        xhr.send(formData);
    });
}

并且两个解决方案都不成功两个解决方案导致CORS错误列出

and both solution weren't successful aka both solution leaded to the CORS error listed above.

我错过了什么,或者如何从Ionic2 / Angular2查询Yelp API v3?

Did I miss something or how could I query the Yelp API v3 from Ionic2 / Angular2?

Thx
最好的祝福

Thx Best regards

PS:请注意,我的OAuth access_token没有公开。

P.S.: Note that my OAuth access_token isn't exposed. The authentication is generated by my backend.

@Thierry Templier后,验证是由我的后端产生的。

UPDATE

回答我找到一个适用于Ionic2的解决方案。

After @Thierry Templier answer I found a solution which works for Ionic2.

在浏览器中调试时,我使用代理查询Yelp API V3。因此我在ionic.config.json文件中添加

When debugging in the browser, I query the Yelp API V3 using a proxy. Therefor I add in ionic.config.json file

 "proxies": [{
    "path": "/yelp/v3/businesses",
    "proxyUrl": "https://api.yelp.com/v3/businesses"
 }]

并执行以下查询

this.http.get('http://localhost:8100/yelp/v3/businesses/' + 'search', ...


$ b b

注意以下内容也可以工作

note that following would also work

this.http.get('/yelp/v3/businesses' + 'search', ...

在iOS和Android中运行时,代理不应该因此我在我的服务中执行以下查询

When running in iOS and Android, the proxy should not be use aka not gonna work. Therefor I do the query like following in my service

this.http.get('https://api.yelp.com/v3/businesses/search, ...

当然,我写了一个gulp任务,允许我在环境之间切换。

Of course, to have something handy, I write a gulp task which allow me to switch between environments.

但是,这个解决方案只适用于Ionic2。如果我需要在网站Angular2 ,我需要我猜一个代理太,不确定。因此,我在Yelp API V3的问题列表中打开了该任务的副本

But, this solution is only applicable for Ionic2. If I would have to implement it in Angular2 in a website, I would need I guess a proxy too, not sure about it. Therefor I opened a copy of that task in the issues list of the Yelp API V3

https://github.com/Yelp/yelp-api-v3/issues/21

推荐答案

问题不是在客户端,因为浏览器会透明地Hamble跨域请求。它将发送 Origin 头。服务器必须处理CORS以下内容:

The problem isn't on the client side since the browser will transparently Hamble cross domain requests. It will send under the hood the Origin header. The server must handle CORS following this:


  • 将CORS标头发送回响应中以启用(或不启用)此类请求。 / li>
  • 如有必要,处理预检请求。

有关详细信息,请参阅此文章:

See this article for more details:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

我查看了v3版本的文档,并且看不到任何关于CORS或JSONP的信息。唯一剩下的解决方案是在服务器应用程序中实现一个代理作为解决方法。我知道这不是理想,但它是唯一可能的解决方案,我看到

I had a look at the docs of the v3 version and can see nothing regarding CORS or JSONP. The only remaining solution is to implement a proxy in your server application as a workaround. I'm aware that it's not ideal but it's the only possible solution I see

这篇关于Angular2 Yelp API CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆