亲测可用。SpringBoot连接VUE或React。
新建包名,在该包名下创建GlobalCorsConfig.Class.
package com.example.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;
import static java.util.Arrays.asList;
import static org.springframework.web.cors.CorsConfiguration.ALL;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin(ALL);
config.setAllowedMethods(asList("GET", "POST", "PUT", "DELETE"));
config.addAllowedHeader(ALL);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
注意:如果爆红,看看包是否导对了。