去年做项目的时候遇到的跨域相关的问题,记下代码以后备用。
后台:
几种做法任选其一即可
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest reqs = (HttpServletRequest) req;
//reqs.getHeader("Origin")可换成ip地址或null
response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
// response.setHeader("Access-Control-Allow-Origin","*");
//允许发送cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
//发送方式
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
//过期时间
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
/**
* spring跨域
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
/**
*spring config配置
**/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
// 设置跨域访问
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE")
.allowCredentials(true)
.maxAge(3600);
}
}
前端:
if (window.XMLHttpRequest){//for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
}else{//for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp .withCredentials = true;//重点
注意:这段代码是前端原生ajax代码,jq代码与这段代码不同。