springboot攔截器導致@CrossOrigin失效。
原因:
1、CROS復雜請求時會首先發送一個OPTIONS請求做嗅探,來測試服務器是否支持本次請求,請求成功后才會發送真實的請求;而OPTIONS請求不會攜帶數據,導致這個請求被攔截了,直接返回了狀態碼,響應頭中沒攜帶解決跨域問題的頭部信息,出現了跨域問題。
方法一:
因此解決方案是把所有的OPTIONS請求統統放行。詳細分析見:https://blog.csdn.net/MrKorbin/article/details/104066979
在preHandle加以下內容:
if("OPTIONS".equals(request.getMethod().toUpperCase())) { return true; }

方法二:
不使用@CrosOrigin注解解決跨域問題,使用過濾器:示例使用CorsFilter,也就是一個封裝了解決跨域問題的filter而已。
package com.pacmp.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @Author * @Date 2020/6/19 15:48 * @Version 版本號 * @Description 描述 */ @Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.setAllowCredentials(true); config.addAllowedMethod("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); return new CorsFilter(configSource); } }
