【问题标题】:Angular 2 Cross Domain RequestAngular 2 跨域请求
【发布时间】:2020-01-07 13:48:46
【问题描述】:

我再次遇到 angular 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);
}

我的应用程序工作得很好,直到我尝试调用我的亚马逊网址,它当然没有“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});
    }

提前致谢!

【问题讨论】:

    标签: angular xmlhttprequest cross-domain


    【解决方案1】:

    this.responseURL 的响应中获取 URL。 检查是否不是 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;
           }
        }
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2018-10-28
      • 2018-10-07
      • 2019-02-22
      • 1970-01-01
      • 2017-11-18
      • 2015-04-24
      • 2017-09-12
      相关资源
      最近更新 更多