代码改变世界

springboot解决跨域

2023-10-25 12:44  小罗世界  阅读(7)  评论(0编辑  收藏  举报
 
新建config包
 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 import org.springframework.web.cors.CorsConfiguration;
 4 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
 5 import org.springframework.web.filter.CorsFilter;
 6 
 7 @Configuration
 8 public class CorsConfig {
 9 
10     // 当前跨域请求最大有效时长。这里默认1天
11     private static final long MAX_AGE = 24 * 60 * 60;
12 
13     @Bean
14     public CorsFilter corsFilter() {
15         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
16         CorsConfiguration corsConfiguration = new CorsConfiguration();
17         corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
18         corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
19         corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
20         corsConfiguration.setMaxAge(MAX_AGE);
21         source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
22         return new CorsFilter(source);
23     }
24 }

 

在建文件复制进去即可
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 {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
重启前后端服务之后就不会报错