【问题标题】:Angular/YouTube API - refused to display: in a frame because it set 'X-Frame-Options' to 'sameoriginAngular/YouTube API - 拒绝显示:在一个框架中,因为它将“X-Frame-Options”设置为“sameorigin”
【发布时间】:2019-12-21 03:41:01
【问题描述】:

我看过很多关于这个问题的帖子,但我看到的只是嵌入的视频,我认为这不是我的情况。我有一个 URL,它应该根据用户的输入为我提供视频,以便可以观看预告片,但错误消息出现在控制台中:

拒绝在框架中显示“https://www.googleapis.com/youtube/v3/search?part=sn-p&q=robocop&topicId=%2Fm%2F02vxn&key=AIzaSyB42WhSTkS6_0uUPX6EuGakkGz4RHXnlIc”,因为它设置了“X-Frame-Options” ' 到 '同源'。

代码如下:

组件:

safeUrl: SafeResourceUrl
  
  constructor(private movieService: MoviesService, private fb: FormBuilder,
    private sanitizer: DomSanitizer) {}

  ngOnInit() {
    
this.safeUrl =  this.sanitizer.bypassSecurityTrustResourceUrl
("https://www.googleapis.com/youtube/v3/search?part=snippet&q=robocop&topicId=%2Fm%2F02vxn&key=AIzaSyB42WhSTkS6_0uUPX6EuGakkGz4RHXnlIc");
  //this is a static URL to provide the robocop movie trailer

HTML:

 <iframe [class.thumbnail]="thumbnail" [src]="safeUrl" width="560" height="315" frameborder="0" webkitallowfullscreen mozallowfullscreen
  allowfullscreen></iframe>

我怎样才能做到这一点?将 URL 粘贴到浏览器上,我得到一个像这样的 json:

{
 "kind": "youtube#searchListResponse",
 "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/cDGghZKnwX2aAUA7AHR1yBLd91k\"",
 "nextPageToken": "CAUQAA",
 "regionCode": "PT",
 "pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/YWtWaXHndgHpHajPoRfWHslrqXc\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "Z931XZ2wfpE"
   },
   "snippet": {
    "publishedAt": "2016-11-13T15:46:31.000Z",
    "channelId": "UCuwxAIqBcP-9W9CNYAAg7KA",
    "title": "RoboCop (1987) - First Mission (1080p) FULL HD",
    "description": "For more RoboCop Videos - https://www.youtube.com/playlist?list=PLainponqoUGNp-P_Jg2359ahWVOJNdKpd.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/Z931XZ2wfpE/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/Z931XZ2wfpE/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/Z931XZ2wfpE/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "RED Lion Movie Shorts",
    "liveBroadcastContent": "none"
   }
  },

【问题讨论】:

    标签: angular api youtube


    【解决方案1】:

    显然,您尝试访问的 url 提供了一个 JSON 响应,该响应具有 items 属性。那里的每个项目都有一个vidoeId,您可能有兴趣将它们显示为列表中的嵌入视频。

    如何使用 HttpClient 请求数据,然后使用 safeUrl 作为 pipe

    在这种情况下,组件的外观如下:

    import { Component } from "@angular/core";
    import { HttpClient } from "@angular/common/http";
    import { Observable } from "rxjs";
    import { map } from "rxjs/operators";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      results$: Observable<Array<any>>;
    
      constructor(
        private http: HttpClient
      ) {}
    
      ngOnInit() {
        this.results$ = this.http.get(
          "https://www.googleapis.com/youtube/v3/search?part=snippet&q=robocop&topicId=%2Fm%2F02vxn&key=AIzaSyB42WhSTkS6_0uUPX6EuGakkGz4RHXnlIc"
        ).pipe(
          map(res => res.items),
          map((items: Array<any>) => {
            return items.map(item => ({
              title: item.snippet.title,
              vidoeUrl: `https://www.youtube.com/embed/${item.id.videoId}`,
            }))
          })
        );
      }
    }
    

    然后您还需要创建一个pipe 来清理网址:

    import { Pipe, PipeTransform } from "@angular/core";
    import { SafeResourceUrl, DomSanitizer } from "@angular/platform-browser";
    
    @Pipe({
      name: "safeUrl"
    })
    export class SafeUrlPipe implements PipeTransform {
      constructor(private sanitizer: DomSanitizer) {}
    
      transform(url: string, args?: any): SafeResourceUrl {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
      }
    }
    

    您最终将遍历 tempate 中的结果列表:

    <ul *ngIf="results$ | async as results; else elseBlock">
      <li *ngFor="let item of results">
        <iframe 
          [class.thumbnail]="thumbnail" 
          [src]="vidoeUrl | safeUrl" 
          width="560"
          height="315" 
          frameborder="0" 
          webkitallowfullscreen
          mozallowfullscreen 
          allowfullscreen>
        </iframe>
      </li>
    </ul>
    
    <ng-template #elseBlock>
      Something went wrong
    </ng-template>
    

    PS:您的 id 是私人的,因此您不应在 StackOverflow 上的问题中分享它。到目前为止,您只会看到出现了一些问题,因为我收到了未经授权的错误。但它应该适合你。

    这里有一个Working Sample Code 供您参考。

    【讨论】:

    • 很好的答案和解释,非常感谢(我忘了隐藏我的钥匙,也感谢您指点那个)干杯!
    • 您好@SiddAjmera,有一个问题,即使使用我的密钥,我在 youtube 屏幕上也出现复制错误我认为这是拼写错误 vidoeId: item.id.videoId, 而不是 videoID(已修复),但它不是.我删除了我的 addBlocker,但视频没有显示,你知道怎么回事吗?
    • @Mellville,我的错。网址应为https://www.youtube.com/embed/${item.id.videoId} 而不是?v=videoId。我已经更新了 StackBlitz,它现在可以工作了。请看一看。对此感到抱歉:)我也更新了答案。
    • 感谢您的关注,现在它确实有效,stackblitz 示例对其他人非常有用/尽管它是我的 API 密钥 :p) 干杯!
    猜你喜欢
    • 2022-11-29
    • 2013-12-28
    • 2017-05-22
    • 2016-10-08
    • 2018-02-22
    • 2018-08-05
    • 2020-11-07
    相关资源
    最近更新 更多