方法一: 对某一接口配置,可以在方法上添加 @CrossOrigin 注解
@CrossOrigin(origins = {"http://localhost:8110", "null"}) // origins 不指定的话,默认为"*",即所有url
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings(HttpServletRequest request,
HttpServletResponse response) {
// 一定要设置以下响应头,否则客户端报错
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
return "Hello World";
}
方法二: 对一系列接口配置,在类上加注解,对此类的所有接口有效
@CrossOrigin(origins = {"http://localhost:8110", "null"}) // 不指定的话,默认为"*",即所有url
@RestController
@RequestMapping("/attendance/user")
public class SpringBootCorsTestApplication {
@PostMapping("/login")
public R login(
@RequestBody
User user,
HttpServletRequest request,
HttpServletResponse response
){
// 一定要设置以下响应头,否则客户端报错
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
... // 逻辑代码
}
}
方法三: 全局配置,添加一个配置类
**第一步**
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}
}
**第二步**
设置web层接口中的响应头,代码与方法一,二相同
方法四: 全局配置,并且在接口中不需要设置响应头
@Configuration
public class CorsConfig1 extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}