省去了使用过滤器什么的配置文件、又是拦截器、又是@Configuration注解
最简单的,直接再springboot启动类上加上相关的代码即可。
代码语言:javascript复制package com.englishcode.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author: YinLei
* Package: com.englishcode.test
* @date: 2021/5/7 17:19
* @Description:
* @version: 1.0
*/
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 跨域配置
* */
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
//允许任何域名、任何请求头、任何方式的提交方法
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
//对所有接口都有效
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}