問題:已被CORS策略阻止:請求的資源上沒有'Access-Control-Allow-Origin'標頭(跨域請求失敗)java
解決方法:使用過濾器設置Access-Control-Allow-Origin解決跨域請求web
第一步: 建立過濾器跨域
package com.ljw.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class SimpleCORSFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; // 指定容許其餘域名訪問 response.setHeader("Access-Control-Allow-Origin", "*"); // 容許全部 // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1, http://locahost"); // 容許白名單IP // 響應類型 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // 預檢請求的結果緩存60分鐘 response.setHeader("Access-Control-Max-Age", "3600"); // 響應頭設置 response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, res); } @Override public void init(FilterConfig arg0) throws ServletException { } }
第二步:web.xml 配置過濾器緩存
<filter> <filter-name>cors</filter-name> <filter-class>com.ljw.filter.SimpleCORSFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
————————————————
版權聲明:本文爲CSDN博主「@不白」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/qq_39726772/article/details/88973362app