我使用Spring實現了其他Web服務。當我將其作爲Spring Boot應用程序部署在Eclipse中時,它可以工作。但是,當我將它部署在同一臺機器上的Tomcat 7中時,它不起作用。該錯誤消息如下:剩餘服務在Eclipse中部署但在Tomcat中不可用
XMLHttpRequest cannot load http://localhost:8080/ristoreService/oauth/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.
我CORS過濾器看起來是這樣的:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, "
+ "Origin,Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
如果我註釋掉response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
,我仍然得到同樣的錯誤。即使我在Eclipse中進行部署,如果沒有這條線,它也無法正常工作。爲什麼它在不同的環境下部署在同一個ip上?
編輯: 我測試的網址http://localhost:8080/ristoreService/oauth/token
休息客戶端測試儀「CocoaRestClient」,得到了404所以我做了起來,這顯然不UI(angularjs)存在http://localhost:8080/xxxxx
並運行它一個網址,並再次得到了CORS錯誤。我認爲這個錯誤是有誤導性的,畢竟是404。但是爲什麼當戰爭部署成功,名稱爲ristoreService.war時,在Tomcat的webapps下卻沒有發現它?
相關:http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-域名 – Kadima
錯誤是什麼? – Ulises
@Ulises在我的文章中提到'對預檢請求的響應沒有通過訪問控制檢查:否請求的資源上存在'Access-Control-Allow-Origin'標頭。 Origin'http://127.0.0.1:8081'因此是不允許訪問的.' – ddd