跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
目前用到两种方式
- 前后端统一通过代理转发,使api和vue web都通过同一域名+端口来访问,以确保同源;
- 通过服务端接口层配置,支持CORS请求;
服务层配置
我们目前前端有Vue、安卓、iOS,后端共用一套,因此更好的方式是通过修改服务层,以支持多端请求。
Spring MVC配置方式
Spring MVC从4.2版本开始增加对CORS的支持,只需要在Controller或Method上添加@CrossOrigin
注解即可,该注解在SpringBoot上添加无效。
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
或者:
# CORSFilter
@Component
public class CORSFilter implements Filter {
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");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
# web.xml
<filter>
<filter-name>cors</filter-name>
<filter-class>com.web.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SpringBoot配置方式
@Configuration
public class CustomCorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许任何域名使用
corsConfiguration.addAllowedOrigin("*");
// 允许任何头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法(post、get等)
corsConfiguration.addAllowedMethod("*");
// 允许发送Cookie
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
或者:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
}
查阅:https://blog.csdn.net/z69183787/article/details/53102112
原文地址:https://www.cnblogs.com/vipinchan/p/10075998.html
时间: 2024-09-30 20:29:06