SpringBoot解决cors跨域问题

1.使用@CrossOrigin注解实现
 (1).对单个接口配置CORS

 @CrossOrigin(origins = {"*"})
@PostMapping("/hello")
@ResponseBody
public ResultVO hello() {
return new ResultVO(1,"成功");
}

(2).对某个Controller下的所有接口配置CORS

@CrossOrigin
@Controller
public class HelloController { }

2.配置全局的CORS

(1)添加配置类

 package com.yltx.api.config;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter; /**
* @Author: Hujh
* @Date: 2019/5/9 15:49
* @Description: Cors跨域配置
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}

(2)添加配置类

 import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /**
* @Author: Hujh
* @Date: 2019/5/9 16:18
* @Description:
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}

注:添加配置类方法取一即可.

上一篇:SpringBoot学习(3)-SpringBoot添加支持CORS跨域访问


下一篇:SpringBoot添加支持CORS跨域访问