當我們需要將spring boot以restful接口的方式對外提供服務的時候,如果此時架構是前後端分離的,那麼就會涉及到跨域的問題,那怎麼來解決跨域的問題了,下面就來探討下這個問題。
解決方案一:在Controller上添加@CrossOrigin註解
使用方式如下:
@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; } }解決方案二:全局配置
代碼如下:
@Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override 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請求,一次真正的請求*/ @Bean 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); }當然,如果微服務多的話,需要在每個服務的主類上都加上這麼段代碼,這違反了DRY原則,更好的做法是在zuul的網關層解決跨域問題,一勞永逸。
關於前端跨域的更多信息,請參考://www.VeVB.COm/article/83093.htm
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。