springboot 允许跨域解决

382 阅读1分钟

问题:spring在WebMvcConfigurer实现类中配置了允许跨域之后仍报异常:

java.lang.IllegalArgumentException: 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.

这时候,大概率是springBoot版本问题.将allowedOrigins("*")改成allowedOriginPatterns("*")即可解决问题.

package com.example.aibinghaosi.config.WebMvcConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 因为 父类WebMvcConfigurationSupport 重写了 extendMessageConverters 方法
 * 覆盖了原方法.导致了 配置文件中的该配置失效  #所有数字返回给前端的时候,都转成字符串 spring.jackson.generator.write-numbers-as-strings=true
 * 所以此处,我们自己重写 extendMessageConverters 方法
 */
@Slf4j
@Configuration
public class WebMvcConfig2 implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")  //springboot 2.3以前版本是 allowedOrigins
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}