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

  


免責聲明!

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



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