Angular2中IFrame的跨域问题 [英] Cross domain issue with IFrame in Angular2

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

问题描述

我们打算访问托管在同一台机器上但在不同端口上的另一个应用程序URL.所以我的Angular 2应用程序 http://localhost:8081/app/试图打开一个托管在同一服务器但不同端口上的站点,即 localhost:9100

We intend to access another app url which is hosted on the same machine, but on different port. So my Angular 2 application http://localhost:8081/app/ is trying to open a site hosted on same server but different port i.e. localhost:9100

We are trying to access following url in an iframe
url = http://localhost:9100/custom/getCustomPage

<iframe id="customFrame" *ngIf="url !== null" frameborder="0" [src]="url"></iframe>

Chrome/Firefox DOM上的错误Exception:阻止了具有原点的框架通过跨域框架访问" http://localhost:9100 ".在 http://localhost:9100/custom/getCustomPage 中,其中Host:localhost:9100 Referer: http://localhost:8081/app/

Error on Chrome/Firefox DOMException: Blocked a frame with origin "http://localhost:9100" from accessing a cross-origin frame. at http://localhost:9100/custom/getCustomPage Where Host:localhost:9100 Referer:http://localhost:8081/app/

我在响应过滤器中添加了以下标头:

I have added below headers to Response Filter:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers: content-length, Allow

请帮助我确定一种解决方法,以便iFrame可以显示结果.

Please help me identify a workaround so that iFrame allows to display the results.

目前在IE 11中运行正常.

This is currently working fine in IE 11.

推荐答案

您必须使用Dom清理程序绕过安全性,将URL作为受信任的URL返回.您可以执行以下操作:

You have to return your URL as a trusted url using Dom sanitizer to bypass security. Here is what you can do:

在您的html中:

<iframe [src]='getSourceURL()'></iframe>

...并在您的打字稿中:

import { DomSanitizer } from '@angular/platform-browser';

@Component({
    ....
})
export class YourComponent {      

    yourIFrameUrl: string;
    constructor(public sanitizer: DomSanitizer) { }

    getSourceURL() {
        return this.sanitizer.bypassSecurityTrustUrl(this.yourIFrameUrl);
    }
}

这篇关于Angular2中IFrame的跨域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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