配置类
在Spring Boot中,通过实现 WebMvcConfigurer 接口,处理跨域请求。
适用场景
适用 简单请求 和 非简单请求
代码
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 CORSConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
解释
允许请求跨域访问
匹配映射url路径,如Controller的 @RequestMapping("/doLogin")
/** 允许所有请求路径跨域访问
addMapping("/**")
允许可访问的前端服务器列表
允许可访问的前端服务器列表,* 表示允许任意服务器
.allowedOrigins("*")
注意:末尾不能有符号: /,如下:
.allowedOrigins("http://192.168.1.10:8080") 只允许 http://192.168.1.10:8080 访问
允许携带的请求头
告诉前端,发请求时,允许携带的请求头,*,表示允许所有请求头
如下:
config.addAllowedHeader("*");
允许请求方法
* 表示允许所有请求方法,如:POST, GET, OPTIONS, DELETE, HEAD, PUT
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
允许携带 cookie
true 表示允许携带 cookie,还需要ajax配合
.allowCredentials(true)
设置 Preflight 请求缓存时间
非简单请求,先发送 OPTIONS 请求,该请求称为:Preflight 预检请求,然后才发送正式请求
该设置表示:在一段时间内,不再发送Preflight 预检请求,以秒为单位
maxAge(3600)
ajax
jquery
$.ajax({
url:baseUrl+'goods/list',
type:'post',
dataType:'json',//服务器端返回的数据格式是json
xhrFields: { //带上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);
})
post请求同上面代码,只需要改 把 get改成post 即可