在springboot项目中如何设置跨域,其实很简单,只需要在Java项目中加一个配置类即可
可以用这种配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${url}")
private String url;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//设置允许跨域的路径
//如果有多个路径需要跨域,只需要将跨域路径放入数组中
//String [] allowDomain={"http://**","http://*","http://*"};
//.allowedOrigins(allowDomain)//多url跨域
.allowedOrigins(url)//设置允许跨域请求的域名
.allowCredentials(true)//是否允许证书 不写默认开启
.allowedMethods("GET","POST","PUT","OPTIONS","DELETE","PATCH") //设置允许的方法
.maxAge(3600);//跨域允许时间
}
}
也可以用这种
import lombok.extern.slf4j.Slf4j;
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 java.util.Arrays;
/**
* 跨域配置类
*/
@Configuration
@Slf4j
public class GlobalCorsConfig {
String[] allowDomain = {"http://localhost:9527","http://localhost:7000"};//运行跨域的路径
@Bean
public CorsFilter corsFilter() {
log.info(Arrays.toString(this.allowDomain));
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
// config.addAllowedOrigin("http://localhost:9527"); //单路径
config.setAllowedOrigins(Arrays.asList(allowDomain)); //多路径
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
二选一