1. 程式人生 > 其它 >springboot跨域設定

springboot跨域設定

1.首先在springboot建立配置檔案CorsConfig.java。如下圖,重啟後可實現跨域,前端無需再配置。

 

 2.java類中內容如下:

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;

@Configuration
public class CorsConfig {

    // 當前跨域請求最大有效時長。這裡預設1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 設定訪問源地址
        corsConfiguration.addAllowedHeader("*"); // 2 設定訪問源請求頭
        corsConfiguration.addAllowedMethod("*"); // 3 設定訪問源請求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 對介面配置跨域設定
        return new CorsFilter(source);
    }
}
———————————————— 版權宣告:本文為CSDN博主「程式設計師青戈」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。 原文連結:https://blog.csdn.net/xqnode/article/details/120947462