Spring 完美配置跨域請求


在SpringBoot2.0 上的跨域 用以下代碼配置 即可完美解決你的前后端跨域請求問題

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 linhongcun
 *
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允許請求帶有驗證信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允許訪問的客戶端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允許服務端訪問的客戶端請求頭*/
        corsConfiguration.addAllowedHeader("*");
        /*允許訪問的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }



}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM