springboot跨域處理

浪天涯&*發表於2024-11-19

註冊跨域過濾器 CorsFilter

@Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOriginPattern("*");//當allowCredentials=true是設定該屬性
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

  驗證:

1、開啟瀏覽器,F12進入控制檯

2、貼上以下程式碼

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8200/user/login', true);
xhr.setRequestHeader('Content-Type', 'application/json');
var data = {"userName": "zs","password": "0192023a7bbd73250516f069df18b500"};
xhr.send(JSON.stringify(data));
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

  

相關文章