springboot跨域問題 和 401
1.跨域
import org. springframework. beans. factory. annotation. Value ;
import org. springframework. boot. web. servlet. FilterRegistrationBean ;
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. core. Ordered ;
import org. springframework. web. cors. CorsConfiguration ;
import org. springframework. web. cors. UrlBasedCorsConfigurationSource ;
import org. springframework. web. filter. CorsFilter ; import java. util. Arrays ;
import java. util. List ; @Configuration
public class CorsConfig { @Value ( "${cors.allowed-origins}" ) private List < String > allowedOrigins; @Bean public FilterRegistrationBean < CorsFilter > corsFilter ( ) { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ( ) ; CorsConfiguration config = new CorsConfiguration ( ) ; allowedOrigins. forEach ( config:: addAllowedOrigin ) ; config. setAllowCredentials ( true ) ; config. setAllowedMethods ( Arrays . asList ( "GET" , "POST" , "PUT" , "DELETE" , "OPTIONS" ) ) ; config. setAllowedHeaders ( Arrays . asList ( "Authorization" , "Content-Type" , "X-Requested-With" ) ) ; config. setMaxAge ( 1800L ) ; source. registerCorsConfiguration ( "/**" , config) ; FilterRegistrationBean < CorsFilter > bean = new FilterRegistrationBean < > ( new CorsFilter ( source) ) ; bean. setOrder ( Ordered . HIGHEST_PRECEDENCE) ; return bean; }
}
application.properties
cors. allowed- origins= 配置跨域放行地址 多個用 , 隔開
2. 解決跨域后 401 報錯 MyWebSecurityConfiguration.java 里面 configure 添加
. antMatchers ( HttpMethod . OPTIONS, "/**" ) . permitAll ( )
再在前端請求中添加 credentials: ‘include’, // 關鍵配置:攜帶跨域憑證 就解決了
前端請求后端 驗證跨域 jsp 方式
async function callFetchRequest ( ) { const url = "http://10.3338.33.30:344/test/test" ; try { const response = await fetch ( url, { credentials: 'include' , headers: { "Content-Type" : "application/json" , } } ) ; if ( ! response. ok) { throw new Error ( `HTTP錯誤 ${ response. status} `) ; } const data = await response. text ( ) ; console. log ( "? 請求成功:" , data) ; document. getElementById ( "result" ) . innerText = "成功:" + data; } catch ( error) { console. error ( "? 請求失敗:" , error) ; document. getElementById ( "result" ) . innerText = "失敗:" + error. message; }
}
在需要驗證的 域名網址下面驗證跨域問題 console 控制臺輸入這個就可以
var xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'GET' , 'http://10.3338.33.30:344/test/test' ) ;
xhr. withCredentials = true ;
xhr. onreadystatechange = function ( ) { if ( xhr. readyState == 4 && xhr. status == 200 ) { console. log ( xhr. responseText) ; }
} ;
xhr. send ( ) ;