@TOC
==处理SpringBoot跨域的三种方式==
1.使用注解
使用@CrossOrigin 注解实现
如果想要对某一接口配置 CORS,可以在相应的方法上添加 @CrossOrigin 注解,如下,==只针对此接口起作用,别的接口还是不能跨域使用==
@RestController
@RequestMapping("/test")
public class RootController {
@CrossOrigin(origins = {"http://localhost:8086", "null"})
@ApiOperation("测试")
@RequestMapping("/hello")
public R test(){
return R.ok().data("msg","Hello World!");
}
}
如果想要对某一类中的接口配置 CORS,可以在相应的类上添加 @CrossOrigin 注解,如下,==只针对此类中的所有接口起作用,别的类下方的接口还是不能跨域使用==
@RestController
@RequestMapping("/test")
@CrossOrigin
public class RootController {
@ApiOperation("测试")
@RequestMapping("/hello")
public R test(){
return R.ok().data("msg","Hello World!");
}
}
2.编写配置类实现
==对全局的接口都起作用==
package com.org.comunity.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrossConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
3.编写Filter实现
可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效
import org.springframework.boot.web.servlet.FilterRegistrationBean;
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;
@Configuration
public class MyConFiguration {
@Bean
public FilterRegistrationBean crosFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:8080");//指定你自己的接口
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
上面三种方式亲测有效,欢迎大家批评斧正