SpringBoot 跨域

SpringBoot 跨域

错误说明

When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

意思是:当 allowCredentials 为 true 时,allowingOrigins 不能包含特殊值 “*”,因为无法在 “Access-Control-Allow-Origin” 响应标头上设置。要允许凭据具有一组来源,请明确列出它们或考虑改用 “allowedOriginPatterns”。

解决

allowingOrigins 换成 allowedOriginPatterns 即可。

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;

@Configuration
public class MallCorsConfiguration {

    @Bean
    public CorsWebFilter corsWebFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        // allowingOrigins 改成 allowedOriginPatterns
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsWebFilter(source);
    }
}

posted @ 2021-08-14 16:27  Java-练习生  阅读(15)  评论(0)    收藏  举报