我有一个使用 Angular 5 前端访问的 Spring Boot 服务器。使用如下所示的代理配置访问后端服务器:
{
"/api/*": {
"target": "http://localhost:8085",
"secure": false,
"changeOrigin": true
}
}
服务器正在设置一些标头并以 ResponseEntity 的形式返回响应。这是针对应该返回下载流的 GET 请求。
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Expose-Headers", "Content-Type, Content-Disposition, Content-Length");
headers.add("Content-Type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
headers.add("Content-Disposition", "attachment; filename=" + FILE_NAME);
.
.
<some-logic-here>
.
.
return new ResponseEntity<>(content, headers, HttpStatus.OK);
在通过 Chrome 调试应用程序时,我可以看到返回的数据以及标头,但由于某种原因,只有内容类型标头被读取,而不是其他标头。
发送请求的客户端代码如下:
export interface FileResult {
body: any[];
headers: {};
}
getFileByteArray(url: string): Observable<FileResult> {
return this.http.get<FileResult>(this.baseUrl + url, this.options);
}
this.service.getFileByteArray(url).subscribe(fileResult => {
this.showSpinner = false;
//var filename = fileResult.headers; <- This is where the headers are not visible
this.downloadFile(fileResult.body, 'temp');
})
通过 Chrome 调试器查看时返回的响应标头
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
allow-control-allow-origin: *
access-control-allow-headers: Origin, Content-Type, Content-Disposition, Content-Length
access-control-expose-headers: Content-Type, Content-Disposition, Content-Length
content-disposition: attachment; filename=Stats_Workbook_01-SEP-2018_01-SEP-2018.xlsx
content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
content-length: 9803
connection: close
不知道为什么它们在上面的代码片段中被重复了两次。