Angular 2跨域请求

时间:2018-02-27 10:45:07

标签: angular xmlhttprequest cors

我再次遇到角度2的问题,我需要你的帮助或提示。

我正致力于在内部应用程序中从Amazon S3下载文件,这意味着"所有"我的请求必须经过身份验证,为此我在app.component.ts

中添加了此功能
public initInterceptor(): void {
    let _that = this;
    (function (open) {
        XMLHttpRequest.prototype.open = function () {
            this.addEventListener('readystatechange', function () {
                if (this.readyState === 4) {
                    switch (this.status) {

                        case 401:
                            _that.logout();
                            break;

                        case 200:
                            let token = this.getResponseHeader('Auth');
                            if (token && token != _that.user.token) {
                                _that.user.token = token;
                            }

                            break;
                    }
                }
            }, false);
            open.apply(this, arguments);
        };
    })(XMLHttpRequest.prototype.open);
}

我的应用程序工作得很好,直到我试着打电话给我的亚马逊网址,这当然没有#34; Auth"标题,因为它是对亚马逊的直接调用,所以我的问题是...有没有办法调用我的亚马逊网址而不检查init拦截器函数中的标头?就像我获取ArrayBuffer的那一刻中止XMLHttpRequest一样。我知道这看起来很奇怪,但添加一个我不使用的标题是没有意义的。

我的下载附件电话

downloadAttachment(downloadUrl: any): Observable<any> {
        return this.http.get(`${downloadUrl._body}`,{responseType: ResponseContentType.ArrayBuffer})
            .map(this.extractFile)
            .catch(error => Observable.throw(error.status));
    }

private extractFile(res: Response): Blob {
        let type = res.headers.get('content-type');
        return new Blob([res['_body']], {type: type});
    }

提前致谢!

1 个答案:

答案 0 :(得分:0)

this.responseURL的回复中获取网址。 检查它是否不是S3 URL,然后提取Auth标头

case 200:
    // replace the URL regex placeholder below
    if(!this.responseURL.match(**<Your S3 URL regex>**){
       let token = this.getResponseHeader('Auth');
       if (token && token != _that.user.token) {
         _that.user.token = token;
       }
    }