SpringBoot支持跨域请求

1.springboot要版本保持在2.5以上

2.添加跨域配置

CorsConfig

import org.springframework.context.annotation.Bean;
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 {

    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowCredentials(true)
                        .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS","PATCH")
                        .allowedHeaders("*")
                        .maxAge(3600);
                WebMvcConfigurer.super.addCorsMappings(registry);
            }
        };
    }
}

3.启动验证测试

百度首页测试
image

原创:做时间的朋友
原文地址:https://www.cnblogs.com/PythonOrg/p/15539172.html