说明
在Spring Boot中,CorsFilter 过滤器,用于处理跨域请求。
适用场景
适用 简单请求 和 非简单请求
Java代码
创建配置类,类名无要求,代码如下:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
// 设置过滤器执行顺序,一定要在校验是否登录过滤器之前执行,所以一般设置优先级较高
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
解释
允许可访问的前端服务器列表
允许可访问的前端服务器列表,* 表示允许任意服务器
注意:末尾不能有符号: /,如下:
config.addAllowedOriginPattern("*");)
config.addAllowedOriginPattern("http://192.168.1.10:8080") 只允许 http://192.168.1.10:8080 访问
允许携带的请求头
告诉前端,发请求时,允许携带的请求头,*,表示允许所有请求头
如下:
config.addAllowedHeader("*");
允许请求方法
* 表示所有请求方法,如:POST, GET, OPTIONS, DELETE, HEAD, PUT
config.addAllowedMethod("*");
允许携带 cookie
true 表示允许携带 cookie,还需要ajax配合
config.setAllowCredentials(true);
设置 Preflight 请求缓存时间
非简单请求,先发送 OPTIONS 请求,该请求称为:Preflight 预检请求,然后才发送正式请求
该设置表示:在一段时间内,不再发送Preflight 预检请求,以秒为单位
config.setMaxAge(3600);
允许请求跨域访问
匹配映射url路径,如Controller的 @RequestMapping("/doLogin")
/**允许所有请求路径跨域访问
source.registerCorsConfiguration("/**", config);
ajax 代码
jquery
$.ajax({
url:baseUrl+'goods/list',
type:'post',
dataType:'json',//服务器端返回的数据格式是json
xhrFields: { // 默认跨域时不携带cookie,需要指明携带cookie
withCredentials: true
},
data: {
"status":1
},//发给服务器端的数据
success:function(res){ //data:服务器端返回给浏览器端的数据
if(res.code==0){
console.log(res)
}else{
alert(res.msg);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
axios
axios.get(
baseUrl+'goods/list?status=1',
{withCredentials: true}//带cookie
).then(function(res){
console.log(res.data);
})
或者
axios.defaults.withCredentials = true;//带cookie
axios.get(baseUrl+'goods/list?status=1').then(function(res){
console.log(res.data);
})
参考:
https://blog.csdn.net/weixin_44837637/article/details/129367441