如何读取响应标头(内容处置)?请分享分辨率。
当我检查 Postman 或 Google Chrome Network 选项卡时,我可以在 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);
}
Run Code Online (Sandbox Code Playgroud)
我已经找到了这个问题的解决方案。根据Access-Control-Expose-Headers,仅公开默认标头。
为了公开“Content-Disposition”,我们需要将“Access-Control-Expose-Headers”标头属性设置为“*”(允许所有)或“Content-Disposition”。
// 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.
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6894 次 |
| 最近记录: |