如何从网站 URL 的响应 Headers 在 Angular 7 中获取 X-Frame-Options 值?

How to get the X-Frame-Options value from a website URL's Response Headers in Angular 7?

我需要查明是否可以在 iFrame 中预览 URL(一些用户会想要此功能 - 并且可能将 url 设置为允许在 iFrame 中显示)。我想检查 DenySameOrigin

X-Frame-Options

我发现了很多使 http 客户端获取 api 请求的示例。但是我无法为我的特定用例找到示例。

在请求 url 之后,我只需要 return headers。以下是我尝试过的众多示例中的一个。

如何使用 Angular 从 URL、client-side 获取 X-Frame-Options 值?

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebUrlPreviewService {
  private requestHeaders: HttpHeaders;

  constructor(private http: HttpClient) {
    this.requestHeaders = new HttpHeaders();
    this.requestHeaders.append('Content-Type', 'application/json');
    this.requestHeaders.append('Accept', 'application/json');
  }

  getResponseHeaders(url: string):Observable<HttpResponse<HttpHeaders>> {
    return this.http.get<HttpHeaders>(url, {observe: 'response'});
  }
}

I just need to return the headers after requesting a url.

如果我对你的问题理解正确,你只想取回 headers。为此,您可以使用 HttpClient 的 HEAD request 仅获取响应的 headers 而无需 body.

什么是HEAD,来自Mozilla docs:

The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method. Such a request can be done before deciding to download a large resource to save bandwidth, for example.

服务

@Injectable({
  providedIn: 'root'
})
export class WebUrlPreviewService {
  private requestHeaders: HttpHeaders;

  constructor(private http: HttpClient) {}

   headRequest(url: string):Observable<any> {
    return this.http.head(url, {observe: 'response'}); //is observe property necessary to make this http call? If not you can remove it.
  }
}

组件

export class AppComponent implements OnInit {

  constructor(private webUrlPreviewService: WebUrlPreviewService){}

  ngOnInit(){
    this.webUrlPreviewService.headRequest("https://api.github.com").subscribe(
      (data: HttpResponse<any>) => {
        console.log(data);
        console.log(data.headers.get('ETag'));
        console.log(data.headers.get('X-Frame-Options'));
      }

    )
  }
}

控制台日志结果

HttpResponse {headers: {…}, status: 200, statusText: "OK", url: "https://api.github.com/"…}

W/"5ce06fd8cae5bfa1bcfcf398e0d07415"

null

如您所见,data.headers.get('X-Frame-Options') returns 为空。那是因为api.github.comHttpHeaders设置了Access-Control-Expose-Headers不暴露X-Frame-Options

例如公开的自定义 headers 不包括 X-Frame-Options。 Access-Control-Expose-Headers →ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type

因此,请注意您的后端应将 Access-Control-Expose-Headers 设置为包含 X-Frame-Options

simple stackblitz demo