原因:
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);
}
}
推薦閱讀
GitHub 下載神器強勢迴歸!
巧用枚舉來幹掉if-else,代碼更優雅!
如何正確訪問Redis中的海量數據?服務纔不會掛掉!
超硬核!1.6W 字 Redis 面試知識點總結,建議收藏!