*一、第一种方式:
1、编写一个支持跨域请求的 Configuration
/**
* @author ChenXc
* @version V1.0
* @Date 2018/3/22 17:25
* @Description TODO(跨域支持)
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
二、 第二种方式(推荐)
第一种存在一个问题,当服务器抛出 500 的时候依旧存在跨域问题
@SpringBootApplication
@ComponentScan
@EnableDiscoveryClient
public class ManagementApplication {
public static void main(String[] args){
SpringApplication.run(ManagementApplication.class, args);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = newCorsConfiguration();
corsConfiguration.addAllowedOrigin("");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addExposedHeader(HttpHeaderConStant.X_TOTAL_COUNT);
return corsConfiguration;
}
/** * 跨域过滤器 * * @return */
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
三、第三种方式,编写 Filter 过滤器
@Component
public class OriginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res); }
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于