2017-02-16 41 views
0

我有一個簡單javax.filter.Filter實現,應該CORS標頭添加到HttpResponse`javax.filter.Filter`不加入CORS標頭正確

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

問題是,如果您在設置標題前調用chain.doFilter(req, res),Tomcat/Jetty將開始編寫響應並且不能添加任何更多標題。不幸的是,兩臺服務器都不會給你一個錯誤信息或異常來表明這一點。

解決方法:始終在呼叫之前設置標頭chain.doFilter(req, res)