response.addHeader(“Access-Control-Allow-Credentials”, “true”);
response.addHeader(“Access-Control-Allow-Origin”, “http://localhost:8080”);
response.addHeader(“Access-Control-Allow-Methods”, “POST, GET, OPTIONS,DELETE,PUT”);
使用方法:
(1)在controller类方法上添加@CrossOrigin注解
@RestController
@RequestMapping("/review")
public class AccountController {
@CrossOrigin
@GetMapping("/{id}")
public String retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
(2)在整个controller类上添加@CrossOrigin
@CrossOrigin(origins = "http://pghhh.top", maxAge = 3600)
@RestController
@RequestMapping("/review")
public class AccountController {
@GetMapping("/{id}")
public String retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
@CrossOrigin中的两个参数:
- origins: 允许可访问的域列表
- maxAge:准备响应前的缓存持续的最大时间(以秒为单位)
通过这种方式,AccountController类下的所有方法都启用了跨域支持。
(3)如果使用了Spring Security,可以在Spring Security中进行配置
请确保在Spring安全级别启用CORS,并允许它利用Spring MVC级别定义的配置。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
3、全局CORS配置
基于WebMvcConfigurerAdapter配置加入Cors的跨域
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有的当前站点的请求地址,都支持跨域访问
.allowedOriginsPatterns("*") // 所有的外部域都可跨域访问。 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名(注意:SpringBoot2.4.0之后【allowedOriginsPatterns】代替【allowedOrigins】)
.allowCredentials(true) // 是否支持跨域用户凭证
.allowedMethods("GET", "POST", "DELETE", "PUT") // 当前站点支持的跨域请求类型是什么
.maxAge(3600); // 超时时长设置为1小时。 时间单位是秒
}
}



