前言
因目前采用前后端分离的写法,当部署了服务器之后,前端web端调用服务器就会产生跨域的问题。
解决方案
springboot官方给出的解决方案为:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowCredentials(true);
}
};
}
}
如果想单独对某个接口做跨域可使用@CrossOrigin
注解
注意
上述方式可以达到跨域的效果,但是由于springboot
采用的方式为在调用DispatchServlet
接口时进行interceptor
拦截,而cros
的interceptor
是放在最后一层,故如果说各位自己写的代码中增加了interceptor
,并且在OPTIONS
的方法执行的时候被前面的某一层拦截下来了,那么就会跨域失败。
- 此时可采用过滤器
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
/* *
* 跨域过滤器
*
* @return
* */
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
- 也可以在自己的
interceptor
中剔除OPTIONS
方法的拦截
@Component
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (CorsUtils.isPreFlightRequest(request)) {
return true;
}
// 拦截处理逻辑
...
}
}
这样就能达到彻底实现跨域的做法了。
小结
- 如果自己的项目中没有增加
interceptor
,可尽情使用springboot
提供的跨域方式 - 如果自己的项目中增加了
interceptor
,可增加corsfilter
进行过滤 - 如果自己的项目中增加了
interceptor
,又不想增加filter
,那么可将OPTIONS
方法从自己的拦截器中剔除