什么是跨域?这里先简单介绍一下-------->跨域指的是当两个路径他们的协议、域名、端口有一个不同就会产生跨域问题,而前端所说的同源策略指的就是协议、域名、端口都相同的情况。
为了支持跨域访问,浏览器设置了预检机制。也就是说在发出跨域请求时, 浏览器会自动发出一个查询请求,称为预检请求, 用来确认目标资源是否支持跨域。
如果请求要满足以下条件,浏览器才不会发送预检请求:
1、请求方法是GET 、PosT .HEAD其中任意一个
2、请求头中包含Accept、Accept-Language、Content-Language、Content-Type、DPR、Downlink、Save-Data、Viewport.Width、Width字段。
3、Content-Type的值是text/plain 、multipart/form-data ,application/x-ww-form-urlencoded 中任意一个。
那如何进行解决呢?这里有几种方法可供你选择
使用注解实现
@GetMapping("/list")
@CrossOrigin
public List<String> list(){...
}
没错,添加@CrossOrigin注解就可以实现跨域问题,但是通过注解实现跨域我暂时还没用过,你们可以试试。
添加过滤器
@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter(){CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**",corsConfiguration);return new CorsFilter(source);}
}
实现WebMvcConfigurer接口
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOriginPatterns( "*").allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTIONS").allowCredentials(true).maxAge(3600).allowedHeaders("*");}
}
只需要重写addCorsMapping() 方法就可以了。相比之下最后一种跨域解决方法更加简洁。
这里如果你的项目是spring项目,可以实现一个过滤器进行跨域
public class CorsFilter implements Filter {@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "x-requested-with");chain.doFilter(req, res);}
}