最近公司做的前后端分離的項目(之前沒有做前后端分離),所以這里就設計到了跨域的問題了
進入主題
Springboot解決跨域的問題很簡單
直接配置一個CorsConfig配置類即可
@Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setMaxAge(3600L); // 預檢請求的有效期,單位為秒。
corsConfiguration.setAllowCredentials(true);// 是否支持安全證書(必需參數)
return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }
不要用WebMvcConfigurerAdapter繼承的方法了,因為已經過時了,Springboot2.0已經不推薦此方法。
此處有一個比較坑的地方就是:
corsConfiguration.setMaxAge(3600L); // 預檢請求的有效期,單位為秒。 corsConfiguration.setAllowCredentials(true);// 是否支持安全證書(必需參數)
這兩句務必要加上,不然無論前端怎么做,也無論后台你對shiro的過濾器怎么重寫,response請求返回狀態都是302。
網絡上大家的代碼都是copy來copy去,往往沒有這2句,所以這個坑真是眼淚汪汪。
參考:https://blog.csdn.net/wangchsh2008/article/details/90324631?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight