Java 后端彻底解决跨域问题(CORS)
接口调用出现跨域问题时,浏览器会报如下提示
XMLHttpRequest cannot load xxx. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
等等信息
直接通过一个过滤器来解决
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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; /** * 允许跨域过滤器(Cross-Origin Resource Sharing) * @author user * */ @Component public class CorsFilter implements Filter { private final Logger logger = Logger.getLogger(this.getClass().getPackage().getName()); 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-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type,Accept," + "content-Type,origin,x-requested-with,content-type,accept,authorization,token,id,X-Custom-Header,X-Cookie,Connection,User-Agent,Cookie,*"); response.setHeader("Access-Control-Request-Headers", "Authorization,Origin, X-Requested-With,content-Type,Accept"); response.setHeader("Access-Control-Expose-Headers", "*"); chain.doFilter(req, response); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
web.xml 文件
<!-- 跨域过滤器 --> <filter> <filter-name>corsFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>corsFilter</filter-name> <url-pattern>/dental/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>corsFilter</filter-name> <url-pattern>/toothCheck/*</url-pattern> </filter-mapping>
原文地址:
https://www.cnblogs.com/poterliu/p/11339942.html