springboot跨域问题解决方案

以下内容仅供自己学习使用,侵权私聊必删。

在进行前后端交互的时候,往往会遇到以下的跨域问题。


那么解决这种跨域的话,可以使用以下这种方法:(引自于程序员青戈)

  1. 创建config配置目录
  2. 新建CorsConfig类
  3. 然后把下面的内容复制进去根据自己需要修改以下就可以解决跨域问题啦
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();
		// 1、直接*号也可以
		corsConfiguration.addAllowedOrigin("*");
		// 2、或者设置访问源地址
        //corsConfiguration.addAllowedOrigin("http://localhost:8080");
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
posted @ 2023-05-11 09:35  Amyel  阅读(346)  评论(0编辑  收藏  举报