后端解决跨域问题
后端解决跨域问题
实现WebMvcConfigurer
@Configuration @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") public class AppConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://www.hhh.com") // 可跨域的域名 .allowCredentials(true) .allowedMethods("*") .allowedHeaders("*"); } }
使用Filter过滤器来过滤服务请求
@WebFilter public class CorsFilter implements Filter { @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-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } }