package com.java456.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class CORSConfiguration extends WebMvcConfigurationSupport { /* * 这里主要为了解决跨域问题,所以重写addCorsMappings方法 */ @Override protected void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .exposedHeaders("access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options") .allowCredentials(false).maxAge(3600); super.addCorsMappings(registry); } }
方式一:配置过滤器(全局配置)
@Configurationpublic class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.setAllowCredentials(true); config.addAllowedMethod("*"); config.addAllowedHeader("*"); config.addExposedHeader("*"); UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); return new CorsFilter(configSource); } }
方式二:配置拦截器 (全局配置)
@Configurationpublic class MyConfiguration extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("*"); } }
方式三: 单个请求的跨域通过 @CrossOrigin 注解来实现
@RequestMapping("/hello")@CrossOrigin("http://localhost:8080") public String hello( ){ return "Hello World"; }
参考资料:https://blog.csdn.net/fxbin123/article/details/80603678
站长微信:xiaomao0055
站长QQ:14496453