Angular5响应标题(内容处理)阅读

时间:2018-05-28 02:06:08

标签: angular-http

如何阅读响应标题(内容处理)?请分享决议。

当我查看Postman或Google Chrome网络标签时,我可以在HTTP调用的响应标题部分看到“Content-Disposition”,但无法读取Angular Code中的标头参数。

// Node - Server JS
app.get('/download', function (req, res) {
  var file = __dirname + '/db.json';
  res.set({
    'Content-Type': 'text/plain',
    'Content-Disposition': 'attachment; filename=' + req.body.filename
  })
  res.download(file); // Set disposition and send it.
});


// Angular5 Code
 saveFile() {
    const headers = new Headers();
    headers.append('Accept', 'text/plain');
    this.http.get('http://localhost:8090/download', { headers: headers })
      .subscribe(
        (response => this.saveToFileSystem(response))
      );
  }

  private saveToFileSystem(response) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition'); // <== Getting error here, Not able to read Response Headers
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    const blob = new Blob([response._body], { type: 'text/plain' });
    saveAs(blob, filename);
  }

3 个答案:

答案 0 :(得分:3)

我找到了解决这个问题的方法。根据{{​​3}},只会公开默认标头。

为了公开“内容处理”,我们需要设置“访问 - 控制 - 展示 - 标题”&#39;标题属性为&#39; *&#39; (允许所有)或&#39;内容处理&#39;。

// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
  'Content-Type': 'text/plain',
  'Content-Disposition': 'attachment; filename=' + req.body.filename,
  'Access-Control-Expose-Headers': 'Content-Disposition' // <== ** Solution **
})
res.download(file); // Set disposition and send it.
});

答案 1 :(得分:0)

此解决方案可帮助我从响应标头获取Content-Disposition。

(data)=>{  //the 'data' is response of file data with responseType: ResponseContentType.Blob.
    let contentDisposition = data.headers.get('content-disposition');
}

答案 2 :(得分:0)

这不是 Angular 的问题,而是 CORS 的问题。

如果服务器没有明确允许您的代码读取标头,则浏览器不允许读取它们。 在服务器中,您必须在响应中添加 Access-Control-Expose-Headers

在响应中,它将类似于 Access-Control-Expose-Headers:,

asp.net core中,可以在startup.csConfigureServices方法中设置CORS时添加>

enter image description here

相关问题