【问题标题】:Not able to get the `Content-Disposition` from backend response无法从后端响应中获取“Content-Disposition”
【发布时间】:2018-06-08 02:49:34
【问题描述】:

我正在尝试从我的后端响应中获取来自 Content-Disposition 的值。但我根本无法做到这一点..

这是我的代码:

public getQuoteImage(sharedQuote):Observable<any> {
    return this.http.post(environment.downloadSummarUrl, JSON.stringify(sharedQuote), { 
      headers: this.params.headers.validate,
      observe: "response",
      responseType : 'blob'
    });
  }

我正在尝试通过以下方式从Content-Disposition 获取filename

downloadSummaryContent() {
    this.server.getQuoteImage(this.sharedQuote).subscribe((data) => {
      console.log( 'headers are', '\n', data, '\n',  data.headers.get('Content-Disposition') ); //but not getting the file name
      var url = window.URL.createObjectURL(data);
      var a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display: none');
      a.href = url;
      a.download = 'quote.pdf';
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove(); // remove the element
    });
  }

但根本没有获得价值。

在我得到的控制台中:

{
  "headers": {
    "normalizedNames": {

    },
    "lazyUpdate": null,
    "lazyInit": null,
    "headers": {

    }
  },
  "status": 200,
  "statusText": "OK",
  "url": "https:XXXXXXservice/p/shipment/download/",
  "ok": true,
  "type": 4,
  "body": {

  }
}

【问题讨论】:

  • CORS 请求仅允许 javascript 访问以下响应标头:Cache-Control Content-Language Content-Type Expires Last-Modified Pragma - 除非响应包含提供 javascript 的 Access-Control-Expose-Headers访问任何其他人的权限 - 请参阅 Documentation
  • 注意:你写的是服务器端吗?因为它特别允许实际上是响应标头的请求标头 - 请求永远不会发送 Access-Control-Allow-* 标头,并且它也“允许”Access-Control-Request-* 标头。但这些都在浏览器的控制之下(从来没有在你的代码中设置),并且根据需要设置并且永远不需要明确允许
  • @JaromandaX - 在我添加 Access-Control-Expose-Headers 后它可以工作 - 谢谢!如果您将您的建议作为答案,我同意。

标签: javascript angular http angular5


【解决方案1】:

根据MDN Access-Control-Expose-Headers documentation,CORS请求只允许javascript访问以下响应头:

  • 缓存控制
  • 内容-语言
  • 内容类型
  • 过期
  • 最后修改
  • 编译指示

服务器可以允许使用Access-Control-Expose-Headers 响应访问其他响应标头,因此,要使客户端可以访问Content-Disposition,您需要发出

Access-Control-Expose-Headers: Content-Disposition

响应中的标题

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2018-10-30
    • 2015-07-23
    • 2017-10-10
    相关资源
    最近更新 更多