1. 程式人生 > 實用技巧 >springboot跨域請求配置

springboot跨域請求配置

springboot跨域請求配置

方式一:

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 { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 允許任何域名使用 corsConfiguration.addAllowedHeader("*"); // 允許任何頭 corsConfiguration.addAllowedMethod("*"); //
允許任何方法(post、get等) corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); //
對介面配置跨域設定 return new CorsFilter(source); } }

方式二:

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration //加配置註解可以掃描到
public class WebConfig implements WebMvcConfigurer{
    
    //跨域請求配置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**")// 對介面配置跨域設定
                .allowedHeaders("*")// 允許任何頭
                .allowedMethods("POST","GET")// 允許方法(post、get等)
                .allowedOrigins("*")// 允許任何域名使用
                .allowCredentials(true);
    }
    
}