Spring-boot中完美实现Post|Spring-boot中完美实现Post,Get方式的跨域请求

由于在javascript页面中请求数据涉及到跨域请求,困扰很久才处理完成,所以记录下来这次操作经验 1.在spring-boot中设置过滤器 ,直接上代码

@Component public class CorsFilter implements Filter {final static org.slf4j.Logger logger = org.slf4j.LoggerFactory .getLogger(CorsFilter.class); public CorsFilter(UrlBasedCorsConfigurationSource source) {}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", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Origin,Content-Type, Accept"); chain.doFilter(req, res); }public void init(FilterConfig filterConfig) { }public void destroy() { } }

2.在Application中配置全局过滤器
/** * 跨域配置 * @return */ private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; }/** * 跨域过滤器 * @return */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); }

【Spring-boot中完美实现Post|Spring-boot中完美实现Post,Get方式的跨域请求】至此完美解决Post的对象请求还有正常的GET方式请求数据,经实践可正常使用

    推荐阅读