當(dāng)我們需要將spring boot以restful接口的方式對外提供服務(wù)的時候,如果此時架構(gòu)是前后端分離的,那么就會涉及到跨域的問題,那怎么來解決跨域的問題了,下面就來探討下這個問題。
解決方案一:在Controller上添加@CrossOrigin注解
使用方式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@CrossOrigin // 注解方式 @RestController public class HandlerScanController { @CrossOrigin (allowCredentials= "true" , allowedHeaders= "*" , methods={RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS, RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins= "*" ) @PostMapping ( "/confirm" ) public Response handler( @RequestBody Request json){ return null ; } } |
解決方案二:全局配置
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping( "/**" ) .allowCredentials( true ) .allowedMethods( "GET" ); } }; } } |
解決方案三:結(jié)合Filter使用
在spring boot的主類中,增加一個CorsFilter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * * attention:簡單跨域就是GET,HEAD和POST請求,但是POST請求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain * 反之,就是非簡單跨域,此跨域有一個預(yù)檢機(jī)制,說直白點(diǎn),就是會發(fā)兩次請求,一次OPTIONS請求,一次真正的請求 */ @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials( true ); // 允許cookies跨域 config.addAllowedOrigin( "*" ); // #允許向該服務(wù)器提交請求的URI,*表示全部允許,在SpringMVC中,如果設(shè)成*,會自動轉(zhuǎn)成當(dāng)前請求頭中的Origin config.addAllowedHeader( "*" ); // #允許訪問的頭信息,*表示全部 config.setMaxAge(18000L); // 預(yù)檢請求的緩存時間(秒),即在這個時間段里,對于相同的跨域請求不會再預(yù)檢了 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); } |
當(dāng)然,如果微服務(wù)多的話,需要在每個服務(wù)的主類上都加上這么段代碼,這違反了DRY原則,更好的做法是在zuul的網(wǎng)關(guān)層解決跨域問題,一勞永逸。
關(guān)于前端跨域的更多信息,請參考:http://www.ythuaji.com.cn/article/137112.html
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/liuchuanhong1/article/details/62237705