java前后端联调经常会出现跨域问题,后端使用postman或者swagger请求是ok的.前端自测也是ok的.一对接就会出问题.这里记录一下后端处理跨域的方法!
把这个类添加到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;
/**
* 解决跨域问题
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
说明:
config.addAllowedOrigin(""); ==> 表示对所有的地址都可以访问
config.setAllowCredentials(true); ==> 最终的结果是可以 在跨域请求的时候获取同一个session
config.addAllowedMethod(""); ==> 跨域的所有请求方法
config.addAllowedHeader("*"); ==> 跨域的所有请求头
configSource.registerCorsConfiguration("/**", config); ==> 所有可以访问的地址
欢迎大佬们留言评论,共同学习!!!感谢!!!
===========================
原创文章,转载注明出处!