1、在springboot2 中,设置前端运行跨域访问只需要在启动类上加一个Bean就行
/**
* 跨域问题
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 允许所有的访问
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setMaxAge(18000L);
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
2、允许单一域名访问,只需要修改 * 变成对应的域名就行
/**
* 跨域问题
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://baidu.com");
config.addAllowedHeader("*");
config.setMaxAge(18000L);
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
3、允许多域名访问
/**
* 跨域问题
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// config.addAllowedOrigin("http://baidu.com");
List list = new ArrayList();
// list添加你需要的域名
list.add("http://baidu.com")
corsConfiguration.setAllowedOrigins(list);
config.addAllowedHeader("*");
config.setMaxAge(18000L);
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
4、跨域访问这样设置了,如果是带token访问的,可能还会遇到一个问题,前端请求之后,后端返回了token给前端,但是没有在response中添加允许放行,导致后续的请求中,token取不到
@Component
@ConditionalOnProperty(
value = {"spring.sleuth.enabled"},
matchIfMissing = true
)
public class ResponseFilter extends ZuulFilter {
@Autowired
private Tracer tracer;
@Override
public String filterType() {
return POST_TYPE;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
String traceId = tracer.currentSpan().context().traceIdString();
ctx.getResponse().addHeader("Trace-Id", traceId);
// 把你要返回到前端的 key 加上,不然前端下一次请求就没有token了
ctx.getResponse().addHeader("access-control-allow-headers", "Authorization,authorization");
ctx.getResponse().addHeader("access-control-expose-headers", "Authorization,authorization");
return null;
}
}