Springboot 攔截器導(dǎo)致 @CrossOrigin 跨域失效的解決方案
原因:
CROS 復(fù)雜請求時會首先發(fā)送一個 OPTIONS 請求做嗅探,來測試服務(wù)器是否支持本次請求,請求成功后才會發(fā)送真實的請求;而 OPTIONS 請求不會攜帶數(shù)據(jù),導(dǎo)致這個請求被攔截了,直接返回了狀態(tài)碼,響應(yīng)頭中沒攜帶解決跨域問題的頭部信息,出現(xiàn)了跨域問題。
方法一:
因此解決方案是把所有的 OPTIONS 請求統(tǒng)統(tǒng)放行。詳細(xì)分析見:https://blog.csdn.net/MrKorbin/article/details/104066979
在 preHandle 加以下內(nèi)容:
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);
????}
}
推薦閱讀
評論
圖片
表情

