自定义响应头无法到达前端,需配置Apache Httpd吗?
自定义响应头通过Apache代理后无法被前端获取的解决方案
我部署了两台服务器:一台是运行UI应用的Apache Httpd服务器(端口80),另一台是Spring Boot应用服务器(端口8080)。Spring Boot接口返回自定义响应头warning,直接用Postman调用该接口能看到该头,但通过Httpd代理后,前端AngularJS代码无法获取到这个自定义响应头。当前Httpd配置仅设置了ProxyPass和ProxyPassReverse,请问是否需要在httpd.conf中添加额外配置?
Spring Boot 代码
final HttpHeaders header = new HttpHeaders(); HttpEntity<byte[]> httpEntity = null; if(true){ header.set("warning", "Some warning message"); httpEntity = new HttpEntity<>(new ConnectorFileVO().getData(), header); return httpEntity; }
AngularJS 前端代码
ProductConfigService.downloadProduct(req).then(function (response) { var warning = null if(response.headers) { warning = response.headers['warning']; } else { console.log('Some error'); } var filename = null; if(response.headers['content-disposition']) { filename = response.headers['content-disposition'].split('filename=')[1]; downloadActualFile(response.data, filename); } deferred.resolve(); }, function (fault) { deferred.reject(fault); toastr.error(fault.faultDescription, $filter('i18n')('error')); }); return deferred.promise;
当前Apache Httpd.conf 配置
SSLProxyEngine on ProxyPass /spring-boot/api/ http://localhost:8080/spring-boot/ ProxyPassReverse /spring-boot/api/ http://localhost:8080/spring-boot/
解决方案
需要添加两项关键配置:
- 确保Apache代理传递后端的
warning响应头:默认情况下Apache代理可能不会传递所有自定义头,需显式配置让代理保留该头:
ProxyPassReverseHeader warning *
- 允许前端访问自定义响应头:由于浏览器的CORS安全策略,自定义响应头默认无法被前端JavaScript获取,需通过
Access-Control-Expose-Headers头声明允许暴露的自定义头:
Header always set Access-Control-Expose-Headers "warning"
最终的Apache配置如下:
SSLProxyEngine on ProxyPass /spring-boot/api/ http://localhost:8080/spring-boot/ ProxyPassReverse /spring-boot/api/ http://localhost:8080/spring-boot/ # 传递后端的warning响应头 ProxyPassReverseHeader warning * # 允许前端获取warning头 Header always set Access-Control-Expose-Headers "warning"
配置完成后重启Apache服务,前端AngularJS代码就能正常获取warning响应头了。
内容的提问来源于stack exchange,提问作者Rijo
相关产品推荐
相关产品推荐

