我有一个简单的javax.filter.Filter
实现,应该将CORS标头添加到HttpResponse
:
log.debug("Headers before adding: {}", response.getHeaderNames());
log.debug("Adding CORS headers to {}", response.getClass().getName());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
log.debug("Headers after adding: {}", response.getHeaderNames());
但是,有时标题不会在响应中结束(根据接收方和日志记录):
DEBUG Headers before adding: [Cache-Control]
DEBUG Adding CORS headers to org.apache.catalina.connector.ResponseFacade
DEBUG Headers after adding: [Cache-Control]
有时会这样做:
DEBUG Headers before adding: []
DEBUG Adding CORS headers to org.apache.catalina.connector.ResponseFacade
DEBUG Headers after adding: [Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers]
我做错了什么?
答案 0 :(得分:0)
问题是,如果在设置标头之前调用chain.doFilter(req, res)
,Tomcat / Jetty将开始编写响应,并且无法再添加标头。不幸的是,两个服务器都不会给你一个错误信息或异常来表示。
解决方案:始终在调用chain.doFilter(req, res)