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



我需要找出是否可以在iframe中预览URL(某些用户将想要此功能 - 并且可能具有一个URL设置以允许在iFrame中显示(。我想检查X-Frame-OptionsDenySameOrigin

的值

我发现了许多使HTTP客户端获得API请求的示例。但是我很难为我的特定用例找到一个示例。

我只需要在请求URL后返回标头。以下是我尝试过的许多示例。

使用Angular?

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

我只需要在请求URL后返回标头。

如果我正确理解您的问题,您只想找回标题。为此,您可以使用httpclient的头部请求只能获取响应的标题,而没有身体。

什么是头,来自Mozilla文档:

如果使用HTTP GET方法请求指定的资源,则HTTP Head方法请求返回的标题。在决定下载大型资源以节省带宽之前,可以做到这样的请求。

服务

@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')返回null。这是因为api.github.com http标头设置了 Access-Control-Expose-Headers 不要公开 X-Frame-Options

例如。暴露的自定义标头不包括X框架选项。 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

简单stackblitz demo

最新更新