當我們需要將spring boot以restful接口的方式對外提供服務的時候,如果此時架構是前后端分離的,那么就會涉及到跨域的問題,那怎么來解決跨域的問題了,下面就來探討下這個問題。
解決方案一:在Controller上添加@CrossOrigin注解
使用方式如下:
-
-
-
public class HandlerScanController {
-
-
-
-
RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS,
-
RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins= "*")
-
-
public Response handler(@RequestBody Request json){
-
-
return null;
-
}
}
解決方案二:全局配置
代碼如下:
-
-
public class MyConfiguration {
-
-
-
public WebMvcConfigurer corsConfigurer() {
-
return new WebMvcConfigurerAdapter() {
-
-
public void addCorsMappings(CorsRegistry registry) {
-
registry.addMapping( "/**")
-
.allowCredentials( true)
-
.allowedMethods( "GET");
-
}
-
};
-
}
-
}
解決方案三:結合Filter使用
在spring boot的主類中,增加一個CorsFilter
-
/**
-
*
-
* attention:簡單跨域就是GET,HEAD和POST請求,但是POST請求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
-
* 反之,就是非簡單跨域,此跨域有一個預檢機制,說直白點,就是會發兩次請求,一次OPTIONS請求,一次真正的請求
-
*/
-
-
public CorsFilter corsFilter() {
-
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
-
final CorsConfiguration config = new CorsConfiguration();
-
config.setAllowCredentials( true); // 允許cookies跨域
-
config.addAllowedOrigin( "*");// #允許向該服務器提交請求的URI,*表示全部允許,在SpringMVC中,如果設成*,會自動轉成當前請求頭中的Origin
-
config.addAllowedHeader( "*");// #允許訪問的頭信息,*表示全部
-
config.setMaxAge( 18000L);// 預檢請求的緩存時間(秒),即在這個時間段里,對於相同的跨域請求不會再預檢了
-
config.addAllowedMethod( "OPTIONS");// 允許提交請求的方法,*表示全部允許
-
config.addAllowedMethod( "HEAD");
-
config.addAllowedMethod( "GET");// 允許Get的請求方法
-
config.addAllowedMethod( "PUT");
-
config.addAllowedMethod( "POST");
-
config.addAllowedMethod( "DELETE");
-
config.addAllowedMethod( "PATCH");
-
source.registerCorsConfiguration( "/**", config);
-
return new CorsFilter(source);
-
}
