Spring Boot 解决 CORS 跨域问题
Spring Boot 跨域 About 2,729 words前后端协调
与前端调试接口时,遇到跨域问题,一般两种解决方式:
- 前端代理请求(
Nginx代理
、webpack代理
等) - 后端处理响应并解决跨域问题
@CrossOrigin
相关属性
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
全局配置
@CrossOrigin
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
单个配置
@CrossOrigin
@PostMapping("/test")
public String test() {
return "ok";
}
Filter
使用javax.servlet
包下的过滤器
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
filterChain.doFilter(servletRequest, servletResponse);
}
}
WebMvcConfigurer
使用springframework.web.servlet
包下的控制器配置
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
CorsFilter
使用springframework.web.filter
包下的跨域过滤器
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//以下三个配置必须要有
corsConfiguration.addAllowedOrigin("*"); // 1. 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2. 允许任何头
corsConfiguration.addAllowedMethod("*"); // 3. 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4. 配置适用于/**下的路径
return new CorsFilter(source);
}
}
Spring Security
Spring Security跨域需要两步,且第二步必须配置WebMvcConfigurer。设置@CrossOrigin无效。
第一步:配置Spring Security
支持跨域。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
第二步:配置WebMvcConfigurer
支持工程跨域。
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
推荐使用
没有Spring Security
框架下推荐使用@CrossOrigin
前端解决可参考
Views: 6,277 · Posted: 2020-02-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...