一、后台
@Configuration
public class CorsMapping implements WebMvcConfigurer {
@Override
/**
* 重新跨域支持方法
* CorsRegistry 开启跨域注册
*/
public void addCorsMappings(CorsRegistry registry) {
//addMapping 添加可跨域的请求地址
registry.addMapping("/**")
//设置跨域 域名权限 规定由某一个指定的域名+端口能访问跨域项目
//.allowedOrigins("http://192.168.102.1:8080/")
.allowedOrigins("*")
//是否开启cookie跨域
.allowCredentials(true)
//规定能够跨域访问的方法类型
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD")
//添加验证头信息 token
.allowedHeaders("*")
//预检请求存活时间 在此期间不再次发送预检请求
.maxAge(3600);
}
}
二、Ajax请求
$.ajax({
type: "post",
url: url,
data: "username="+username+"&password=" + password,
xhrFields: {
withCredentials: true
},
success: function(data){
alert(data);
}
});
在Ajax请求中加上:
xhrFields: {
withCredentials: true
}