前后端分离之后,前端和后端都拥有自己独立的服务器,但是服务器之间可能为了完成某些业务逻辑,就存在服务器之间的跨域访问
跨域问题的原因就是违背了同源策略:即客户端协议、域名、端口号和服务器存在不同
前后端分离的情况下,在凡是需要前后端交互的Controller身上,添加注解@CrossOrigin
可以作用在整个Controller类上,也可以作用在特定的一个方法上
@Configuration
public class CORSConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:63343","http://127.0.0.1:5500")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE","OPTIONS")
.allowedHeaders("*")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(true);
super.addCorsMappings(registry);
}
}
或者
@Configuration
public class CORSConfiguration {
private CorsConfiguration corsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig());
return new CorsFilter(source);
}
}
//允许客户端发送cookie信息
@CrossOrigin(allowCredentials = "true")
axios.defaults.withCredentials = true
$.ajax({
type:"POST",
url:url,
data:{data,data},
dataType:"json",
xhrFields: {withCredentials: true}, //与服务器配合使用标识允许携带cookie
success:function(data){
},
error:function(XMLHttpRequest){
},
});