springboot允許跨域配置

方式一

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .maxAge(3600);
    }
}

方式二


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域配置
 * @author admin
 * @date 2020/6/19  1:04
 */
@Configuration
public class CorsConfig{
	@Bean
	public CorsWebFilter corsWebFilter(){
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		// 配置跨域
		corsConfiguration.addAllowedHeader("*"); // 所有請求頭 都允許跨域
		corsConfiguration.addAllowedMethod("*"); // 所有方法 都允許跨域
		corsConfiguration.addAllowedOrigin("*"); // 運行所有請求來源跨域
		corsConfiguration.setAllowCredentials(true); // 是否允許攜帶cookie跨域
		source.registerCorsConfiguration("/**",corsConfiguration);
		CorsWebFilter corsWebFilter = new CorsWebFilter(source);
		return corsWebFilter;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章