项目中遇到跨域问题你们怎么处理的呢,这里提供cors跨域作为参考
,项目使用springboot,具体逻辑就不说了,很简单,搜索一下就懂了,这里直接上代码吧
package com.cui.boot.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @author tian * @description cors跨域 * @create 2019-01-24 17:00 */ @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); //1 corsConfiguration.addAllowedOrigin("*"); //2 corsConfiguration.addAllowedHeader("*"); //3 corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); //4 source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }
或者
package com.cui.boot.config; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @author tian * @description cors跨域处理 * @resource https://www.cnblogs.com/cityspace/p/6858969.html * @resource https://www.jianshu.com/p/f9c21da2c661 * @create 2019-01-24 17:10 */ public class SimpleCorsConfig { /** * 设置 跨域请求参数,处理跨域请求 * * @return */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); // 允许跨域访问的域名 corsConfiguration.addAllowedOrigin("*"); // 请求头 corsConfiguration.addAllowedHeader("*"); // 请求方法 corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.POST); corsConfiguration.addAllowedMethod(HttpMethod.GET); corsConfiguration.addAllowedMethod(HttpMethod.PUT); corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS); // 预检请求的有效期,单位为秒。 corsConfiguration.setMaxAge(3600L); // 是否支持安全证书 corsConfiguration.setAllowCredentials(true); return corsConfiguration; } }
其实配置都差不多,能解决问题的就是好代码,上述配置选一个就可以
下面是参考链接,感觉老哥的启发【https://www.cnblogs.com/cityspace/p/6858969.html】