Angular/YouTube API - 拒绝显示:在框架中,因为它将 'X-Frame-Options' 设置为 'sameorigin

Angular/YouTube API - refused to display: in a frame because it set 'X-Frame-Options' to 'sameorigin

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

Refused to display 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=robocop&topicId=%2Fm%2F02vxn&key=AIzaSyB42WhSTkS6_0uUPX6EuGakkGz4RHXnlIc' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

代码如下:

组件:

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"
   }
  },

显然,您尝试点击的 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 来清理 url:

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);
  }
}

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

<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 是私人的,所以你不应该在 Whosebug 上的问题中分享它。截至目前,您只会看到出现错误,因为我收到未经授权的错误。但它应该适合你。

Here's a Working Sample Code for your ref.