1. CORS介绍
跨域资源共享向来都是热门的需求,我们可以使用 CORS 来快速实现 跨域访问,只需要在服务端进行授权即可,无需在前端添加额外的设置
简单说,CORS是一种访问机制,英文全称: Cross-Origin Resource Sharing,即我们说的跨域资源共享。当一个资源从与该资源本身所在服务器不同的域或端口请求一个资源时,资源会发起一个跨域HTTP请求。比如,在一个域名下的网页中,调用另一个域名中的资源。
2. 实现 CORS 跨域请求的方式
对于 CORS的跨域请求,主要有以下几种方式可供选择:
- 返回新的CorsFilter---全局CORS配置
- 重写 WebMvcConfigurer---全局
- 使用注解
@CrossOrigin---局部
- 手动设置响应头 (HttpServletResponse)---局部
注意:
- CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应于springBoot 1.3版本以上
- 前两种方式属于全局 CORS 配置,后两种属性局部 CORS配置。如果使用了局部跨域是会覆盖全局跨域的规则,所以可以通过
@CrossOrigin
注解来进行细粒度更高的跨域资源控制。
2.1 返回新的 CorsFilter(全局跨域)
在任意配置类,返回一个 新的 CorsFIlter Bean ,并添加映射路径和具体的CORS配置路径。
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//允许哪些原始域进行跨域访问
config.addAllowedOrigin("*");
//是否发送 Cookie
config.setAllowCredentials(true);
//放行哪些请求方式
config.addAllowedMethod("*");
//放行哪些原始请求头部信息
config.addAllowedHeader("*");
//暴露哪些头部信息
config.addExposedHeader("*");
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
}
2.2 重写 WebMvcConfigurer(全局跨域)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//是否发送Cookie
.allowCredentials(true)
//放行哪些原始域
.allowedOrigins("*")
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}
2.3 使用注解@CrossOrigin(局部跨域)
在控制器上使用注解 @CrossOrigin:
@RestController
@CrossOrigin(origins = "*")
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
}
在Controller方法上使用注解 @CrossOrigin:
@RequestMapping("/hello")
@CrossOrigin(origins = "*")
public String hello() {
return "hello world";
}
2.4 手动设置响应头(局部跨域)
使用 HttpServletResponse 对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里 Origin的值也可以设置为 "*",表示全部放行。
@RequestMapping("/index")
public String index(HttpServletResponse response) {
response.addHeader("Access-Allow-Control-Origin","*");
return "index";
}
参考:SpringBoot 实现前后端分离的跨域访问(CORS)、springboot系列文章之实现跨域请求(CORS)