springboot跨域問題 HTTP訪問控制(CORS)

1.錯誤描述

其實就仍是我上個guacamole項目的衍生問題,由於要提供一個供外界訪問的接口,當前端頁面填入我在其餘服務器上佈置的guacamole server的地址的時候(我用的firefox瀏覽器)在控制檯能夠清楚地看到html

CORS 頭缺乏 'Access-Control-Allow-Origin'

這些字樣前端

2.解決

這裏先上解決方法,試了好多種只有這個能夠web

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class GlobalCorsConfig extends WebMvcConfigurerAdapter {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader("Content-Type");
        corsConfiguration.addExposedHeader( "X-Requested-With");
        corsConfiguration.addExposedHeader("accept");
        corsConfiguration.addExposedHeader("Origin");
        corsConfiguration.addExposedHeader( "Access-Control-Request-Method");
        corsConfiguration.addExposedHeader("Access-Control-Request-Headers");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

建立這個類,而後在須要進行跨域的類上面加上註解@CrossOrigin
跨域問題就解決了!具體原理我還沒理解,理解了補上,這裏貼一下幫我解決問題的網址:https://www.w3xue.com/exp/article/20193/23459.htmlspring

相關文章
相關標籤/搜索